【问题标题】:Passing self to function within initialization of object in python在python中的对象初始化中将self传递给函数
【发布时间】:2014-02-21 07:18:11
【问题描述】:

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

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 获得 2 个参数?也许有更合乎逻辑的方法来解决这个问题?

【问题讨论】:

    标签: python class tree initialization


    【解决方案1】:

    当你说

    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
    

    【讨论】:

      【解决方案2】:

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

      def setParent(self, np)
      
      def addChild(self, nc)
      

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

      【讨论】:

        猜你喜欢
        • 2014-08-17
        • 1970-01-01
        • 2011-09-13
        • 2022-07-19
        • 2016-02-25
        • 2021-03-02
        • 1970-01-01
        • 2011-10-16
        • 2017-05-13
        相关资源
        最近更新 更多