0

I want to create a python class which implements an overloading constructor, but I'm not sure that my approach is the correct one (I catch the "AttributeError: can't set attribute" error). I have read something recently about using *args and **kwargs placeholders, but I want to see an implementation of this in my case. Here is the code:

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))
  • 1
    tl;dr the duplicate, use **parameter defaults** instead, i.e. `def __init__(self, code, parent=None): if parent is not None: self.children = []; ...` – wjandrea Jun 20 '20 at 18:55
  • 1
    BTW making `self.code` not settable doesn't make any sense. Maybe you want to make it read-only? i.e. in `__init__`, `self._code = code`, then in the property, `return self._code` – wjandrea Jun 20 '20 at 18:58

1 Answers1

-1

I'm new to Stack Overflow. Here is my attempt. I had to use _code in the init otherwise it produced the '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))