我想简单地列出各种各样的咖啡,但是得到一个错误,说明列表没有定义。在引用类变量时,是否必须在构造函数中使用self
?
我已经尝试更改return
语句以返回self.coffelist.append(name)
,但随后又出现了另一个错误:'Function' object has no attribute 'append'
。
class coffe:
coffelist = []
def __init__(self,name,origin,price):
self.name = name
self.origin = origin
self.price = price
return (self.coffelist.append(self.name))
def coffelist(self):
print(coffelist)
c1=coffe("blackcoffe","tanz",55)
c2=coffe("fineroasted","ken",60)
这是因为您将一个方法命名为coffelist
。
我认为这说明了如何做你想做的事。我还修改了你的代码,以遵循PEP 8 - Style Guide for Python Code并纠正了一些拼写错误的单词。
class Coffee: # Class names should Capitalized.
coffeelist = [] # Class attribute to track instance names.
def __init__(self,name,origin,price):
self.name = name
self.origin = origin
self.price = price
self.coffeelist.append(self.name)
def print_coffeelist(self):
print(self.coffeelist)
c1 = Coffee("blackcoffee", "tanz", 55)
c1.print_coffeelist() # -> ['blackcoffee']
c2 = Coffee("fineroasted", "ken", 60)
c1.print_coffeelist() # -> ['blackcoffee', 'fineroasted']
# Can also access attribute directly through the class:
print(Coffee.coffeelist) # -> ['blackcoffee', 'fineroasted']
是的,谢谢,这正是我想要的!我不确定..我认为你可以在return语句中同时做两件事,两者都返回附加。我觉得很多时候python很灵活,有时候不灵活。谢谢