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:
Python Programming Bootcamp: Go from zero to hero

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. Rick
    - June 17, 2015

    Thanks. staticmethod() function looks very useful in this code.

  2. Chi Ngo
    - June 8, 2015

    Just run the example and ho message was displayed. Can you help resolving it?

    1. Frank
      - June 8, 2015

      Hi, could you provide some more information?

  3. Sourabh
    - June 1, 2015

    why isn’t there a constructor ?? And what if we don’t use a static method. can’t we do it like this
    obj = car(“some name”)

    1. Frank
      - June 1, 2015

      Hi, it’s not neccesary to explicitly define a constructor, unless you want to add logic at object creation like setting parameters. A class always has them.

      If we do not use static method we cannot access the Factory Method (def factory) from outside the class. The idea is to have one method that returns new objects. Given an input string received from network, events or otherwise, this factory methods can create new objects at runtime. We don’t want to create objects that have factories in them, that would be very confusing. obj.factory.drive() would not create a new object that drives, you need to give it the type of object to create.

      Think of it like a physical factory. If you call a factory, it can return several products (objects), but it does not create products with factories inside each product.

  4. Shea Sitz
    - May 30, 2015

    Ok, assert is for debugging purposes and staticmethod() is a decorator. Still doing research but I understand it would be too much to put in a response here.

    1. Frank
      - May 30, 2015

      Hi, answer is by using static we can access a function in a class without creating an object. More detailed answer below.

  5. Shea Sitz
    - May 30, 2015

    What does the assert keyword do, and what does the factory = staticmethod( factory ) do? I have yet to see staticmethod() anywhere in the code. Thanks for your help!

    1. Frank
      - May 30, 2015

      assert is used to debug. A static method can be accessed in a class, without creating an object. That is to say, we can call the function in the class without making a new object. On the bottom of the code you see:

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

      but Car is the class name. Thus, by using static we can access a function in a class as if it were a function.
      An example of static method:

      class Example:
      def add(a,b):
      return a+b

      add = staticmethod(add)

      print Example.add(2,3)

Nowhere in this code we created an object of the class Example. We can call add(2,3) because it is a static method. Normally we create objects from a class.
  1. Andy
    - August 1, 2015

    factory = staticmethod(factory)
    if you delete this line, the code also works.
    I think python knows car.factory() is a static method, just because we define the method without a parameter SELF.
    Am I right ? I’m just a beginner of python.

  • Justin
    - May 30, 2015

    What is the meaning of:
    from __future__ import generators

    1. Frank
      - May 30, 2015

      Hi Justin, this is just an import of the __future__ module. It is not neccesary for this example so I removed it. Thanks!

  • Leave a Reply

    Login disabled