新的类实例继承了以前的实例值

时间:2018-10-26 15:30:15

标签: python class attributes

我正在编写一个实现双向链接列表的小树类:

class node(object): 
def __init__(self, level=0, pieces=0, parent=None,
             root=None, childNo=None, avgN=2): 

    self.level       = level   # Current level in the tree. Zero = top.
    self.pieces      = pieces  # Number of children. Can be constant or Poisson chosen random.
    self.parent      = parent  # Parent of this node.
    self.child       = {}      # Children of this node. Using a dictionary means
                               # the root could have direct access\
                               # to all children.
    self.childrenID  = {}
    self.myID        = childNo # This node's index in the parents self.child list.

    if (root == None):         # If I'm the root, then hey, I'm the root!
        self.root   = self
    else:
        self.root   = root

    self.avgN          = avgN
    self.numOfChildren = 0
    self.pieces        = self.avgN



def print_all_data(self):
    print "Printing all data for node:",self.myID
    obj_attr = [a for a in dir(n) if not a.startswith('__') and not callable(getattr(n,a))]
    for ob in obj_attr:
        print ob, getattr(n,ob)
    return


# This function acutally adds a child node to this parent.
def add_child_node(self, childno):

    self.numOfChildren        += 1
    if (self.numOfChildren > self.pieces):
        print "Error: number of children exceeds the number of assigned pieces"
        print "       for node:", self.myID

    childno                             = self.compute_new_child_ID(self.level, self.numOfChildren)
    self.childrenID[self.numOfChildren] = childno
    self.child[childno]                 = self.get_new_node(childno)

    return

def get_new_node(self,childno):

    return node(level=self.level+1, parent=self,
                root=self.root, childNo=childno,
                avgN=self.avgN)

def compute_new_child_ID(self, level, childno):
    return (level+1)*100 + childno
def get_child_no_from_child_ID(self, level, childID):
    return childID - (level+1)*100

请注意,某些功能看起来是重复的,但它们是供以后使用的占位符。

现在,如果我创建一个实例,我将得到:

n = node()
n.print_all_data()

Printing all data for node: None
avgN 2
child {}
childrenID {}
level 0
myID None
numOfChildren 0
parent None
pieces 2
root <__main__.node object at 0x7fb33dc0ae10>

但是,添加任何子代都会导致它们继承父代的属性:

n.add_child_node(0)
n.add_child_node(1)
n.print_all_data()

Printing all data for node: None
avgN 2
child {101: <__main__.node object at 0x7fb33dc46350>, 102: <__main__.node object at 0x7fb33dc460d0>}
childrenID {1: 101, 2: 102}
level 0
myID None
numOfChildren 2
parent None
pieces 2
root <__main__.node object at 0x7fb33dc0ae10>

这是子数据:

n.child[101].print_all_data()

Printing all data for node: 101
avgN 2
child {101: <__main__.node object at 0x7fb33dc46350>, 102: <__main__.node object at 0x7fb33dc460d0>}
childrenID {1: 101, 2: 102}
level 0
myID None
numOfChildren 2
parent None
pieces 2
root <__main__.node object at 0x7fb33dc0ae10>

创建一个新节点也会继承此旧实例数据:

n2 = node()
n2.print_all_data()

Printing all data for node: None
avgN 2
child {101: <__main__.node object at 0x7fb33dc46350>, 102: <__main__.node object at 0x7fb33dc460d0>}
childrenID {1: 101, 2: 102}
level 0
myID None
numOfChildren 2
parent None
pieces 2
root <__main__.node object at 0x7fb33dc0ae10>

现在,我已经在StackOverflow上进行了全面搜索,而我不是failing to use init (these are instance attributes)也不是improperly initializing an immutable dictionary in the function definition(进一步解释了here)。我在SO中找不到其他与我的问题匹配的示例,因此提出了新问题。非常感谢您的协助。

1 个答案:

答案 0 :(得分:4)

实例是正确的,您只是在打印错误的数据。

在方法print_all_data中,您始终打印由变量n 引用的实例的属性(该实例继承自更高范围,并且始终引用您的不管在什么实例中使用“根”节点),而不是打印当前实例的属性(self参考)。

在方法print_all_data中,您需要类似以下内容(当前实例由变量self 引用):

obj_attr = [a for a in dir(self)
            if not a.startswith('__') and not callable(getattr(self, a))]