Tag: beginner
Introduction
Welcome to my Python Course!
Python is a general-purpose computer programming language.
This course is suitable for both Python 2 and Python 3.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Download Python
To run Python code, you will need one of these programs:
For terminal only: Apple Mac OS X, Microsoft Windows, Linux/UNIX
<caption id=”attachment_3478” align=”alignnone” width=”300”]
Run Python code
A python program should be save as a file with a .py extension.
Try this code:
print("Hello World!") |
Expected output:
Hello World! |
If you are using the interpreter use:
python program.py |
python factory
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.
|
Output:
Racecar driving. |
If you are new to Python programming, I highly recommend this book.