Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中创建多个构造函数?_Python_Constructor_Overloading - Fatal编程技术网

如何在Python中创建多个构造函数?

如何在Python中创建多个构造函数?,python,constructor,overloading,Python,Constructor,Overloading,我想创建一个实现重载构造函数的python类,但我不确定我的方法是否正确(我发现了“AttributeError:can't set attribute”错误)。我最近读了一些关于使用*args和**kwargs占位符的文章,但我想在我的例子中看到这方面的实现。代码如下: class Node(object): def __init__(self, code): self.code = code self.parent = None def __init__(sel

我想创建一个实现重载构造函数的python类,但我不确定我的方法是否正确(我发现了“AttributeError:can't set attribute”错误)。我最近读了一些关于使用*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))

我不熟悉堆栈溢出。这是我的尝试。我必须在init中使用_代码,否则它会生成“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))

tl;删除重复项,改用参数默认值,即
def\uuuu init\uuu(self,code,parent=None):如果parent不是None:self.children=[]BTW making
self.code
不可设置没有任何意义。也许你想让它成为只读的?i、 e.在
\uuuu init\uuuu
中,
self.\u code=code
,然后在属性中,
返回self.\u code