简体   繁体   中英

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?

check this more understanding about is keyword 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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