【问题标题】:How to call a class method using an instance of a different class in Python?如何在 Python 中使用不同类的实例调用类方法?
【发布时间】:2014-01-05 23:47:34
【问题描述】:

我正在尝试使用两个类 - 节点和二叉树来实现二叉树。当我插入节点(左或右)时,我使用insert_left_nodeinsert_right_node 方法,它们是class BinaryTree 的方法,但我也使用class Node 创建一个节点。每次插入节点后,返回当前对象。

现在,我如何使用返回的对象调用 BinaryTree 类的插入方法 - current。例如。在代码的倒数第二行,语句 n3 = n1.insert_left_node(33)AttributeError: 'Node' object has no attribute 'insert_left_node'

失败

我需要另一种方法来实现这一点。

代码:

class Node(object):
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None


class BinaryTree(object):
    def __init__(self, root=None):
        self.root = Node(root)

    def insert_left_node(self, data):
        if not self.root:
            self.root = Node(data)
        else:
            current = self.root
            while True:
                if current.left:
                    current = current.left
                else:
                    current.left = Node(data)
                    break
            return current

    def insert_right_node(self, data):
        if not self.root:
            self.root = Node(data)
        else:
            current = self.root
            while True:
                if current.right:
                    current = current.right
                else:
                    current.right = Node(data)
                    break
            return current

if __name__ == '__main__':
    r = BinaryTree(34)  # root
    n1 = r.insert_left_node(22)
    n2 = r.insert_right_node(45)
    n3 = n1.insert_left_node(33)  # Fails
    print n3

【问题讨论】:

标签: python class python-2.7 tree binary-tree


【解决方案1】:

您的请求实际上没有任何意义。要实现您想要的,您只需将所需的方法添加到您要使用的类中。尝试类似以下的操作:

class Node(object):
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

    def insert_left_node(self, data):
        self.left = Node(data)

    def insert_right_node(self, data):
        self.right = Node(data)

【讨论】:

  • 没关系!但是可以使用 Node 对象调用方法吗?
  • @Shankar 是的,这些方法应该在Node 对象上调用,因为它们是Node 的方法。即:您的示例将正确编译和运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-21
相关资源
最近更新 更多