如何在 Python 中创建多个构造函数? [复制]
Posted
技术标签:
【中文标题】如何在 Python 中创建多个构造函数? [复制]【英文标题】:How can I create a multiple constructor in Python? [duplicate] 【发布时间】: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
【参考方案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))
【讨论】:
以上是关于如何在 Python 中创建多个构造函数? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Python 中创建多个 for 循环列表的递归以获得组合? [复制]