mr.6
mr.6

Reputation: 41

not able to print instance using def __str__ , in a class?

I'm learning Python and currently learning Classes. I'm not able to print the instance of a class, the code is as follows.

class CreditCard:
""" This is properly intended, but CNTRL+K resulted in unindentation
     (stackoverflow's cntrl+k)"""


def __init__(self,customer,bank,account,limit):
    """ Initializing the variables inside the class
        Setting the Initial Balance as Zero
        Customer : Name of the Customer
        bank : Name of the Bank
        balance : will be zero, initial
        account : accoount number or identifier, generally a string
        limit : account limit/ credit limit
    """
    self.customer = customer
    self.bank = bank
    self.accnt=account
    self.limit = limit
    self.balance = 0

def get_customer(self):
    """ returns the name of the customer """
    return self.customer

def get_bank(self):
    """ returns the Bank name """
    return self.bank

def get_account(self):
    """ returns the Account Number """
    return self.account

def get_limit(self):
    """ returns the Credit Limit """
    return self.limit

def get_balance(self):
    """ returns the Balance """
    return self.balance

def charge(self,price):
    """ swipe charges on card, if sufficient credit limit
        returns True if  transaction is processed, False if
        declined """
    if price + self.balance > self.limit:
        return False
    else:
        self.balance=price+self.balance
        # abve can be written as
        # self.balance+=price
        return True
    def make_payment(self,amount):
        """ cust pays money to bank, that reduces balance """
        self.balance = amount-self.balance
        # self.balance-=amount

    def __str__(self):
        """ string representation of Values """
        return self.customer,self.bank,self.account,self.limit

I'd run that with no error. I've created an instance,

 cc=CreditCard('Hakamoora','Duesche',12345678910,5000)

this is what I've been getting.

    >>> cc
      <__main__.CreditCard instance at 0x0000000002E427C8>

what should I include to make it print the instance, like

>>cc=CreditCard('Hakamoora','Duesche',12345678910,5000)
>>cc
>>('Hakamoora','Duesche',12345678910,5000)

Kindly use less technical terms(Newbie here)

pastebinlink : https://paste.ee/p/rD91N

also tried these,

        def __str__(self):
            """ string representation of Values """
            return "%s,%s,%d,%d"%(self.customer,self.bank,self.account,self.limit)

and

           def __str__(self):
                """ string representation of Values """
                return "({0},{1},{2},{3})".format(self.customer,self.bank,self.account,self.limit)

Thanks,
6er

Upvotes: 0

Views: 994

Answers (5)

mr.6
mr.6

Reputation: 41

The is the corrected code, I've learned a grea concept today, learnt about repr and str.

Example for class

Credit card

class CreditCard:
""" Just a Normal Credit Card """

def __init__(self,customer,bank,account,limit):
    """ Initializing the variables inside the class
        Setting the Initial Balance as Zero
        Customer : Name of the Customer
        bank : Name of the Bank
        balance : will be zero, initial
        account : accoount number or identifier, generally a string
        limit : account limit/ credit limit
    """
    self.customer = customer
    self.bank = bank
    self.account=account
    self.limit = limit
    self.balance = 0

def get_customer(self):
    """ returns the name of the customer """
    return self.customer

def get_bank(self):
    """ returns the Bank name """
    return self.bank

def get_account(self):
    """ returns the Account Number """
    return self.account

def get_limit(self):
    """ returns the Credit Limit """
    return self.limit

def get_balance(self):
    """ returns the Balance """
    return self.balance

def charge(self,price):
    """ swipe charges on card, if sufficient credit limit
        returns True if  transaction is processed, False if
        declined """
    if price + self.balance > self.limit:
        return False
    else:
        self.balance=price+self.balance
        # abve can be written as
        # self.balance+=price
        return True
def make_payment(self,amount):
    """ cust pays money to bank, that reduces balance """
    self.balance = amount-self.balance
    # self.balance-=amount

def __str__(self):
    """ string representation of Values """
    return str((self.customer,self.bank,self.account,self.limit))

Thank you so much

Upvotes: 0

Yurrit Avonds
Yurrit Avonds

Reputation: 406

Is the file really indented properly? The last two methods (make_payment and __str__) are indented as if they are a part of the 'charge'-method.

I tested this on my system and the indentation on these two methods (especially __str__) caused the same error as yours. Removing the indentation allowed me to print the 'cc' variable the way you want it.

Upvotes: 0

jez
jez

Reputation: 15349

Three points:

(1) Ensure that the indentation level of your definition of __str__ is such that it's a method of the CreditCard class. Currently it seems to be a function defined locally inside charge() and hence maybe not accessible as an instance method (But it's hard to tell for sure: charge() itself and its fellow methods are also incorrectly indented.)

(2) In __str__, return a string, rather than a tuple:

def __str__(self):
    """ string representation of Values """
    return str( ( self.customer,self.bank,self.account,self.limit ) )

(3) Define an additional __repr__ method: this will be used when displaying the object with

>>> cc

whereas __str__ will only be used when somebody (like print) tries to coerce the object to a str. Here's a minimal example:

def __repr__( self ): return str( self )

Upvotes: 2

Blender
Blender

Reputation: 298166

You're mixing up __str__ and __repr__. Consider the following class:

class Test(object):
    def __str__(self):
        return '__str__'

    def __repr__(self):
        return '__repr__'

You can see which method is called where:

>>> t = Test()
>>> t
__repr__
>>> print(t)
__str__
>>> [1, 2, t]
[1, 2, __repr__]
>>> str(t)
'__str__'
>>> repr(t)
'__repr__'

Also, make sure both of those methods return strings. You're currently returning a tuple, which will cause an error like this to come up:

TypeError: __str__ returned non-string (type tuple)

Upvotes: 5

Chad S.
Chad S.

Reputation: 6633

You forgot to turn the object into a string (or print it).

Try instead:

print(cc)

or

str(cc)

Upvotes: 1

Related Questions