PythonII - Class

A class is a template for creating objects (a custom data structure), providing initial values for attributes(properties) and methods (a function belonging to an object).

Here’s a conceptual example for e.g., a chair.

The attributes are all the data that can define a chair. The behaviours represent all the effects that a chair can produce.


Class basic synthax

To define a class:

class MyClassChair:
    number_of_legs = 4
    material = "Timber"
    is_foldable = False

    def move(self):
        print("Chair is moved.")
    
    def flip(self):
        print("Chair is fliped!")

    def squeak(self):
        print("Squeeak..")


Where,


Istantiate a class

To create an object, use the name of the class followed by round parenthesis.

my_class_chair = MyClassChair()


Note that my_class_chair is named with the snake_case style because it’s a variable.


Access/Modify properties

To access properties add a . to your object variable and type the property you wish to access.

chair_material = my_class_chair.material


By calling the object’s property its value is copied and assigned to a new variable. If you later modify this variable, the original property will remain unchanged.

To modify the class’s properties call the property and assign a new value.

my_class_chair.material = "Plastic"

Access methods

To access properties add a . to your object variable and type the method you wish to call.

my_class_chair.squeak()

Constructor

A constructor is a special class method that is automatically called when an object is created. It is used to initialize the attributes of the object. This method can be called with __init__().

class MyClassChair:
    def __init__(self, number_of_legs, material, is_foldable ):
        self.number_of_legs = number_of_legs
        self.material = material
        self.is_foldable = is_foldable

    def move(self):
        print("Chair is moved.")
    
    def flip(self):
        print("Chair is fliped!")

    def squeak(self):
        print("Squeeak..")

my_class_chair = MyClassChair(4, "Timber", False)
my_class_chair.squeak()  # output: "Squeeak.."


This will force the creation of the object with all the parameters. Without an inital value the interpreter will throw an error.

To instantiate an object without initial parameters you can assign a None (or another value) as a default constructor’s parameter. By doing this, you will be able to create the object without initial values for its properties and assign them later.


Inheritance

Inheritance is a mechanism that allows a new class to inherit the properties and methods of an existing class. The new class is called a derived class, and the pre-existing class is called a base class.

class BaseClassChair:
    def __init__(self,
                 number_of_legs=4,
                 material="Timber",
                 is_foldable=True):
        self.number_of_legs = number_of_legs
        self.material = material
        self.is_foldable = is_foldable

    def move(self):
        print("Chair is moved.")
    
    def flip(self):
        print("Chair is fliped!")

    def squeak(self):
        print("Squeeak..")

class DerivedClassChair(BaseClassChair):
    def __init__(self):
        BaseClassChair.__init__(self)
    
    def rock(self):
        print("Rocking")

derived_class_chair = DerivedClassChair()
derived_class_chair.rock()  # output: "Rocking"


If you don’t overwrite functions or properties already present in the base class they can be accessed from the derived one.

derived_class.foo()  # output: "Hello x2"
print(derived_class.x)  # output: 5