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

时间:2016-01-04 18:36:48

标签: python python-2.7 oop

我正在学习Python并且正在学习类。 我无法打印类的实例,代码如下。

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

我没有错误地运行它。 我创建了一个实例,

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

这就是我所得到的。

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

我应该包含哪些内容来打印实例,例如

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

请使用较少的技术术语(新手在这里)

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

也试过这些,

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

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

谢谢,
6ER

5 个答案:

答案 0 :(得分:5)

您正在混淆__str____repr__。考虑以下课程:

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

    def __repr__(self):
        return '__repr__'

您可以在以下位置查看调用哪种方法:

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

另外,请确保这两个方法都返回字符串。你现在正在返回一个元组,这会导致出现这样的错误:

TypeError: __str__ returned non-string (type tuple)

答案 1 :(得分:2)

三点:

(1)确保__str__定义的缩进级别使其成为CreditCard类的方法。目前它似乎是一个在 charge()内部本地定义的函数,因此可能无法作为实例方法访问(但很难确定:charge()本身它的同伴方法也被错误缩进。)

(2)在__str__中,返回一个字符串,而不是一个元组:

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

(3)定义一个额外的__repr__方法:在使用

显示对象时将使用此方法
>>> cc

__str__仅在某人(如print)试图将对象强制转换为str时使用。这是一个最小的例子:

def __repr__( self ): return str( self )

答案 2 :(得分:1)

您忘记将对象转换为字符串(或打印它)。

尝试改为:

print(cc)

str(cc)

答案 3 :(得分:0)

文件是否真正缩进?最后两个方法(make_payment和__str__)缩进,就好像它们是&#39; charge&#39; -method的一部分。

我在我的系统上对此进行了测试,这两种方法的缩进(尤其是__str__)导致了与您相同的错误。删除缩进允许我打印&#39; cc&#39;改变你想要的方式。

答案 4 :(得分:0)

这是更正的代码, 我今天学会了一个grea概念,了解 repr str

的示例

信用卡

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))

非常感谢