2

可能的重复:
为什么属性引用在 Python 继承中会像这样?
Python:派生类访问同一内存位置中基类的字典

让我们看代码:

class parent:
    book = {'one':1, 'two':2}

class child(parent):
    pass

first = child()
second = child()

print first.book
print second.book

second.book['one'] = 3

print first.book
print second.book

当您运行此对象时,“首先”已编辑其字典!怎么回事?我认为“第一”和“第二”是“孩子”类的独立实例。这里发生了什么?为什么您在第二次编辑的内容首先会影响?

我可以通过在每个子类中重新创建书籍来“解决”这个问题,但这不是正确的方法,我想以它们应该被使用的方式利用类。

我究竟做错了什么?

顺便说一句,我的主要语言是 cpp,所以也许我将 cpp 与 python 或类似的愚蠢混淆了......

任何帮助将不胜感激!

4

3 回答 3

2

您将 book 声明为父类的静态变量。这意味着在加载模块时变量被初始化。

您希望在创建类时对其进行初始化,因此您需要init方法,该方法是在构造每个实例时自动调用的方法。

您还需要手动调用父级 init

class parent:
    def __init__(self):
        self.book = {'one':1, 'two':2}

class child(parent):
    def __init__(self):
        parent.__init__(self)

first = child()
second = child()

print first.book
print second.book

second.book['one'] = 3

print first.book
print second.book
于 2012-08-26T04:48:40.970 回答
2

为了给类的每个实例它自己的字典和名字簿,你需要使用self符号。

class parent:
    def __init__(self):
        self.book = {'one':1, 'two':2}

class child(parent):
    pass

first = child()
second = child()

print first.book
print second.book

second.book['one'] = 3

print first.book
print second.book

输出:

>>> 
{'two': 2, 'one': 1}
{'two': 2, 'one': 1}
{'two': 2, 'one': 1}
{'two': 2, 'one': 3}
>>> 
于 2012-08-26T04:48:45.760 回答
1

Python 在处理类定义时初始化这些类范围变量,然后始终使用相同的对象。

如果您希望字典对每个实例都是唯一的,请在对象构造期间通过实现来分配它__init__

于 2012-08-26T04:45:21.330 回答