简体   繁体   English

python 中的 Inheritance 问题与 python 树库 (anytree)

[英]Inheritance issue in python with a python tree library (anytree)

When I instanciate several nodes, I notice that default attributes which are not specified are then shared between different instanciations.当我实例化几个节点时,我注意到未指定的默认属性随后在不同实例之间共享。 Why?为什么?

from anytree import NodeMixin

class TaskBase:

    def __init__(self, name: str = "default_name", id: int = 1, dependency: str = ""):
        self.name = name
        self.id = id
        self.dependency = dependency


class Task(TaskBase, NodeMixin):

    def __init__(self, name: str = "default_name", id: int = 1, parent=None, children=None):
        super().__init__(name=name, id=id)
        self.parent = parent
        if children:
            self.children = children

if __name__ == "__main__":
    task0 = Task(id=1)
    task1 = Task(id=2, parent=task0)
    task2 = Task(id=3, parent=task0)

In the console, here are the results of several tests:在控制台中,以下是几个测试的结果:

>>> task0 is task1
False

>>> task0.children is task1.children
False

>>> task0.name is task1.name
True

>>> task0.id is task1.id
False

Why task0.name does point to the same object as task1.name while task0 and task1 are two different objects?为什么task0.name确实指向与 task1.name 相同的object而 task0 和 task1 是两个不同的对象?

check this more understanding about is keyword is检查这个关于is关键字的更多理解

>>  class Task():
...     def __init__(self, name: str = "default_name"):
...         self.name = name
... 
task0 = Task('name0')

>>  task1 = Task('name1')
task2 = Task('name1')

>>  task0.name is task1.name
False

>>  task1.name is task2.name
True

  



task0.name and task1.name are same object, because name of each tasks are located the same place, but task0 and task1 are difference object, because they are located different places of memory task0.name 和 task1.name 相同 object,因为每个任务的名称都在同一个地方,但是 task0 和 task1 是不同的 object,因为它们位于不同的地方

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM