我正在学习Python,目前正在学习Classes.我无法打印类的实例,代码如下.
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
你混淆__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)