python logo

python factory

Python hosting: Host, run, and code Python in the cloud!

In Python, there are scenarios where you might not know the exact objects you’ll need to create beforehand. This could be due to dynamic runtime conditions or user interactions. In such situations, the factory method pattern comes to the rescue.

Why Use the Factory Method?
The factory method pattern offers a way to create objects without specifying the exact class of object that will be created. It provides the following advantages:

  1. Dynamic Creation: Objects are created only when they are required based on runtime conditions.
  2. Flexibility: It can easily accommodate new object types without significant changes to the existing code.
  3. Cleaner Code: Helps in maintaining a cleaner and more organized code by separating the object creation process.

Some real-world scenarios where you might leverage the factory method include:

  • A user interacts with an application, and their actions dictate the creation of specific objects.
  • An application might need to dynamically generate multiple documents, each of a different type.
  • In a web browser, where each new tab represents a distinct object, the browser wouldn’t know beforehand the number of tabs a user might open.

Note: If you are keen on mastering Python, consider checking out the Python Programming Bootcamp: Go from zero to hero.

Deep Dive: Factory Method Pattern
The core idea of the factory method pattern is to have a centralized function or method that takes some input and returns an object based on that input.

Here’s a basic example in Python:

obj = Car.factory("Racecar")

In the above code snippet, the factory method of the Car class creates an object based on the input string “Racecar”.

Key Takeaway: The factory method is used to return new object instances. The specific type of object returned depends on the input provided to the factory. This not only makes the code more dynamic but also allows for easier extensibility. New developers can introduce new object types by just adding a new string-to-class mapping without delving deep into the existing codebase.

An Illustrative Example
Let’s delve deeper with a practical example to better understand the factory method pattern:

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.")
# Using the factory method to create an object
obj = Car.factory("Racecar")

When executed, the above code would output:

Racecar driving.

If you’re keen to test and practice more, you can Download Exercises here.

If you’re looking for more topics or previous lessons, navigate Back or move Next.

Leave a Reply:

Justin Sat, 30 May 2015

What is the meaning of:
from __future__ import generators

Frank Sat, 30 May 2015

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

Shea Sitz Sat, 30 May 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!

Shea Sitz Sat, 30 May 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.

Frank Sat, 30 May 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.

Frank Sat, 30 May 2015

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

Sourabh Mon, 01 Jun 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")

Frank Mon, 01 Jun 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. 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.

Chi Ngo Mon, 08 Jun 2015

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

Frank Mon, 08 Jun 2015

Hi, could you provide some more information?

Rick Wed, 17 Jun 2015

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

Andy Sat, 01 Aug 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.

Nathan Sat, 12 Dec 2015

What is a static method?

Frank Sun, 13 Dec 2015

A method you can call without instantiating a class.

Tapan Hegde Mon, 12 Jun 2017

What is the significance the below expression in above code...?
" assert 0, "Bad car creation: " + type"

Frank Tue, 13 Jun 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

Harish Raghav Sat, 01 Jul 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.

Frank Thu, 06 Jul 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.

kaleswaraRao Nallapuneni Wed, 26 Jul 2017

Simple Example .. with nice explanation :)