python - python类的奇怪行为

标签 python class constructor initialization

<分区>

这是一个 python 类:

class TxdTest(object):
    def __init__(self, name = '', atrributes = []):
        self.name = name
        self.attributes = atrributes

然后我像这样使用它:

def main():
    for i in range(3):
        test = TxdTest()
        print test.name
        print test.attributes
        test.name = 'a'
        test.attributes.append(1)

那么,结果如何呢?结果是:

[]

[1]

[1, 1]

为什么类中的'self.attributes'仍然获取值?

最佳答案

将可变对象(如列表)传递给 Python 中的函数或方法时,会在函数或方法的所有调用中使用单个对象。这意味着每次调用该函数或方法(在本例中为您的 __init__ 方法)时,每次都会使用完全相同的列表,并保留之前所做的修改。

如果你想将一个空列表作为默认值,你应该执行以下操作:

class TxdTest(object):
    def __init__(self, name = '', atrributes = None):
        self.name = name
        if attributes is None
             self.attributes = []
        else:
             self.attributes = attributes

有关其工作原理的详细说明,请参阅:“Least Astonishment” in Python: The Mutable Default Argument ,如 bgporter 所述。

关于python - python类的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8145971/

相关文章:

java - 如何检查类的注释是否属于特定类别?

c# - 在 Inherited Class Constructor C# 中强制部分基初始化(和方法)(就像抽象对方法所做的那样)——解决这个问题

c# - 在 C# 中使构造函数仅接受具有 [Serializable] 属性的对象

c# - 如何告诉继承类不要调用其基类的无参数构造函数?

python - 无法插入mysql数据库

python - 将顶部主要 x 刻度的位置更改为底部轴的函数

python - Cython:初始化结构化 Numpy 数组 ValueError

python - 通过 python 使用 win32com 抓取 excel 文件中的图表对象并将其转换为图像

c++ - C++中的具体类是什么?

c++ - 为什么不能使用 'link' 作为类名