Factory method

We may not always know what kind of objects we want to create in advance.
Some objects can be created only at execution time after a user requests so.

Examples when you may use a factory method:

  • A user may click on a certain button that creates an object.

  • A user may create several new documents of different types.

  • If a user starts a webbrowser, the browser does not know in advance how many tabs (where every tab is an object) will be opened.

Related Course:
Complete Python Bootcamp: Go from zero to hero in Python 3

Factory method pattern

To deal with this we can use the factory method pattern.
The idea is to have one function, the factory, that takes an input string and outputs an object.

obj = Car.factory("Racecar")

Key fact: a factory method returns (new) objects.

The type of object depends on the type of input string you specify. This technique could make your program more easily extensible also. A new programmer could easily add functionality by adding a new string and class, without having to read all of the source code.

Factory method example

The example below demonstrates a factory method. The factory method (named factory) returns a new object of either type depending on the input.

class Car(object):

def factory(type):
if type == "Racecar":
return Racecar()
if type == "Van":
return Van()

factory = staticmethod(factory)

class Racecar(Car):
def drive(self):
print("Racecar driving.")

class Van(Car):
def drive(self):
print("Van driving.")

# Create object using factory.
obj = Car.factory("Racecar")


Racecar driving.

Download Exercises


20 thoughts on “Factory method

  1. Jeff Silverman
    - January 11, 2018

    What Frank wrote is true. However, the original code is poorly written, it is not “pythonic”.

       assert 0, "Bad car creation: " + type

    is completely equivalent to

        raise AssertionError("Bad car creation: " + type)

    but the second version is much clearer. The intent of the programmer is that if the code ever gets to this spot, then there is a software error. The assert statement includes a test, but none is needed in this case.

  2. kaleswaraRao Nallapuneni
    - July 26, 2017

    Simple Example .. with nice explanation 🙂

  3. Harish Raghav
    - July 1, 2017

    i am a beginner , mainly from C++ background. I saw a static factory method(method not in any class in 3.6) , in which (A& B class)

    def getXY(par)
    a=dict(key1=A(), key2=B())
    return a[par]

    so, I want to ask , whenever this function(getXY()) will get called ,
    will it create a dictionary object again and again and hence, class object (class A& B) again, on every function call.
    if not , what is the code flow with function call.

    1. Frank
      - July 6, 2017

      After adding a colon to the function, this will return “TypeError: unhashable type: ‘dict'”. You can return a, but not a[par].
      Each time the method is called, it creates A() and B() in the local scope.

  4. Tapan Hegde
    - June 12, 2017

    What is the significance the below expression in above code…?
    ” assert 0, “Bad car creation: ” + type”

    1. Frank
      - June 13, 2017

      Assertions exist in many languages, you’re telling the program to test the condition.
      If an condition is not met, it will throw an assertion error.
      Lets say you want to create an object of a non-existent type:

      c = Car.factory("OK")

      The assertion then makes sure that doesn’t happen

      AssertionError: Bad car creation: OK

  5. Nathan
    - December 12, 2015

    What is a static method?

    1. Frank
      - December 13, 2015

      A method you can call without instantiating a class.

Leave a Reply

Login disabled