简体   繁体   English

无法在类中使用def __str__打印实例?

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

I'm learning Python and currently learning Classes. 我正在学习Python,目前正在学习课程。 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 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 6er

You're mixing up __str__ and __repr__ . 您正在混淆__str____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)

Three points: 三点:

(1) Ensure that the indentation level of your definition of __str__ is such that it's a method of the CreditCard class. (1)确保__str__定义的缩进级别是CreditCard类的一种方法。 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.) 当前,它似乎是一个 charge() 内部局部定义的函数,因此可能无法作为实例方法访问(但是很难确定: charge()本身及其其他方法也被缩进了。)

(2) In __str__ , return a string, rather than a tuple: (2)在__str__ ,返回一个字符串,而不是一个元组:

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 (3)定义一个附加的__repr__方法:当显示带有

>>> cc

whereas __str__ will only be used when somebody (like print ) tries to coerce the object to a str . __str__仅在有人(例如print )试图将对象强制为str Here's a minimal example: 这是一个最小的示例:

def __repr__( self ): return str( self )

You forgot to turn the object into a string (or print it). 您忘记了将对象变成字符串(或打印它)。

Try instead: 请尝试:

print(cc)

or 要么

str(cc)

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. 最后两种方法(make_payment和__str__)缩进为好像它们是“收费”方法的一部分。

I tested this on my system and the indentation on these two methods (especially __str__) caused the same error as yours. 我在系统上对此进行了测试,并且这两种方法(尤其是__str__)的缩进引起了与您相同的错误。 Removing the indentation allowed me to print the 'cc' variable the way you want it. 删除缩进使我可以按所需方式打印“ cc”变量。

The is the corrected code, I've learned a grea concept today, learnt about repr and str . 这是更正后的代码,我今天已经学到了一个很棒的概念,了解了reprstr

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 非常感谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM