简体   繁体   English

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

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

I have a class which represents a node of a tree-like structure which stores it's parent node and any children nodes 我有一个类,代表一个树状结构的节点,该节点存储其父节点和任何子节点

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)

For automation purposes, when the node's created, I want it to call the addChild method of the parent node to add itself to the children list, but as is when a node is initialized with a parent in this manner, I get the error: TypeError: addChild() takes exactly 1 argument (2 given) 为了自动化,在创建节点时,我希望它调用父节点的addChild方法以将自身添加到子节点列表中,但是像这样以父方式初始化节点时,出现错误: TypeError: addChild() takes exactly 1 argument (2 given)

How is it getting 2 arguments from self ? 它如何从self得到两个论点? Perhaps there is a more logical way to approach this? 也许有一种更合理的方法来解决这个问题?

When you say 当你说

p.addChild(self)

Python will make a call to addChild like this Python将像这样调用addChild

addChild(p, self)

because addChild and setParent are instance methods. 因为addChildsetParent是实例方法。 So, they need to accept the current object on which they are invoked as the first parameter, 因此,他们需要接受在其上被调用的当前对象作为第一个参数,

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

You need to make self the first argument of class methods. 您需要将self作为类方法的第一个参数。

def setParent(self, np)

def addChild(self, nc)

You should also definitely read this: http://docs.python.org/2/tutorial/classes.html 您也绝对应该阅读以下内容: http : //docs.python.org/2/tutorial/classes.html

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

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