Python Class

Python support Objection Oriented Paradigm as the other languages such as Java, C++, Smalltalk. In Python, an object create be created as the following:

>>> objA = A( )
>>> objA.<method>    or objA.<attribute>

Normally, an object can be create from its definition which is Class. A class define ever-thing an object need to have such as attributes and methods.

How to define class in Python?
In the part, we will give an complete example of how to create a class using Python. Supp-ose we want to create a class Train which is represented as the following UML diagram.

A train is define by its label. For example, train A, train B…etc. To maintain the current speed of the train, we need to have attribute speed. To speed up the train, we need to have a method speed up which is the incrementation of the attribute speed. Whereas the method slow down decrement the value of speed attribute. A train must be assigned to a driver whose the name will be recorded to the attribute driver.

Here is the code in Python which define the above class.

Note: Every method of the class must have at least a special variable self. _ _init_ _ is the constructor of the class Train. All the attributes of the class are all public. There is a way to make method, or attribute private. It is the use of _ _ before the name of the att-ribute or method.
Did you like this? Share it:

Random Posts

Leave a Reply