如何将列表用作类变量,以便将实例对象(参数)附加到列表中?

2024-09-26 22:08:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想简单地列出各种咖啡,但得到一个错误,说明该列表没有定义。引用类变量时,是否必须在构造函数中使用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)

Tags: nameself列表return定义def错误function
3条回答

是的,谢谢,这正是我想要的! 我不确定。。我认为在return语句中可以同时做两件事,都是return-append。我想python的时间分配是非常灵活的,有时不是。谢谢

这是因为您将其中一个方法命名为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']

相关问题 更多 >

    热门问题