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

问题描述 投票:0回答:3

我想简单地列出各种各样的咖啡,但是得到一个错误,说明列表没有定义。在引用类变量时,是否必须在构造函数中使用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)
python list class-variables
3个回答
0
投票

这是因为您将一个方法命名为coffelist


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']

0
投票

是的,谢谢,这正是我想要的!我不确定..我认为你可以在return语句中同时做两件事,两者都返回附加。我觉得很多时候python很灵活,有时候不灵活。谢谢

© www.soinside.com 2019 - 2024. All rights reserved.