简体   繁体   中英

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)

How is it getting 2 arguments from 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

addChild(p, self)

because addChild and setParent are instance methods. 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.

def setParent(self, np)

def addChild(self, nc)

You should also definitely read this: http://docs.python.org/2/tutorial/classes.html

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