pythonoopclassfactory-patternnamed-constructor

What to return in Factory Methods?


I have a class Node which I want it to have multiple constructors.

I was reading online about factory methods and apparently, it is the cleanest Pythonic way of implementing constructors. My class looks as follows so far:

class Node(object):
  element = None
  left = None
  right = None

  def __init__(self, element):
    self.element = element

  @classmethod
  def tree(cos, element, left, right):
    self.element = element
    self.left = left
    self.right = right
    # return here

What am I supposed to return here though? All examples I saw online had only one assignment and they would return that very assignment. I have three assignments. What is appropriate to return here?


Solution

  • In a named constructor (factory method), you should create an object that you want to return. E.g.

    class Node(object):
        def __init__(self, element):
            self.element = element
            self.left = self.right = None
    
        @classmethod
        def tree(cls, element, left, right):
            node = cls(element)
            node.left = left
            node.right = right
            return node
    

    Note that you don't need the class members, and having class members with the same name as instance members is a bad idea.