繁体   English   中英

在python中的对象初始化内将self传递给函数

[英]Passing self to function within initialization of object in python

我有一个类,代表一个树状结构的节点,该节点存储其父节点和任何子节点

class Node:
    def __init__(self,n, p):
        self.name = n
        self.parent = p
        self.children = []
        if p != None:       
            p.addChild(self)

    def setParent(np):
        if np != None:
            self.parent = np


    def addChild(nc):
        if nc != None:
            children.append(nc)

为了自动化,在创建节点时,我希望它调用父节点的addChild方法以将自身添加到子节点列表中,但是像这样以父方式初始化节点时,出现错误: TypeError: addChild() takes exactly 1 argument (2 given)

它如何从self得到两个论点? 也许有一种更合理的方法来解决这个问题?

当你说

p.addChild(self)

Python将像这样调用addChild

addChild(p, self)

因为addChildsetParent是实例方法。 因此,他们需要接受在其上被调用的当前对象作为第一个参数,

def setParent(self, np):
    ...
def addChild(self, np):
    ...
    self.children.append(nc)    # You meant the children of the current instance

您需要将self作为类方法的第一个参数。

def setParent(self, np)

def addChild(self, nc)

您也绝对应该阅读以下内容: http : //docs.python.org/2/tutorial/classes.html

暂无
暂无

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

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