【问题标题】:How can I create a multiple constructor in Python? [duplicate]如何在 Python 中创建多个构造函数? [复制]
【发布时间】:2020-10-10 21:17:22
【问题描述】:

我想创建一个实现重载构造函数的 python 类,但我不确定我的方法是否正确(我发现“AttributeError:无法设置属性”错误)。我最近阅读了一些关于使用 *args 和 **kwargs 占位符的内容,但我想在我的案例中看到它的实现。代码如下:

class Node(object):
  def __init__(self, code):
    self.code = code
    self.parent = None
  
  def __init__(self, code, parent):
    self.code = code
    self.parent = parent
    self.children = []

  @property
  def code(self):
    return self.code

vertex1 = Node(1)
vertex2 = Node(2, vertex1)
print(str(vertex1.code) + " " + str(vertex2.code))

【问题讨论】:

  • tl;dr 复制,使用 parameter defaults 代替,即def __init__(self, code, parent=None): if parent is not None: self.children = []; ...
  • 顺便说一句,使self.code 不可设置没有任何意义。也许你想让它只读?即在__init__self._code = code,然后在属性中,return self._code

标签: python constructor overloading


【解决方案1】:

我是 Stack Overflow 的新手。这是我的尝试。我必须在 init 中使用 _code 否则它会产生“AttributeError: can't set attribute”。

class Node(object):
    def __init__(self, *args):
        self._code = args[0]
        if len(args) == 1:
            self.parent = None
        else:
            self.parent = args[1]
            self.children = []
    @property
    def code(self):
        return self._code

vertex1 = Node(1)
vertex2 = Node(2, vertex1)
print(str(vertex1.code) + " " + str(vertex2.code))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 2013-04-29
    • 2020-08-01
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    相关资源
    最近更新 更多