我只想简单列出各种咖啡的清单,但会收到一条错误消息,指出该清单未定义。引用类变量时,是否必须在构造函数中使用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)
答案 0 :(得分:0)
这是因为您将一种方法命名为coffelist
。
答案 1 :(得分:0)
我认为这表明了如何做自己想做的。我还修改了您的代码以遵循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']
答案 2 :(得分:0)
是的,这正是我想要的! 我不确定..我以为您可以在return语句中同时做两件事,都返回append。我猜想python的分配时间非常灵活,有时甚至不是。谢谢