Product SiteDocumentation Site

Chapter 11. Class

11.1. Your first class
11.2. __init__ method
11.3. Inheritance
11.4. student_teacher.py
11.5. Multiple Inheritance
11.6. Deleting an object
What is a class? In our daily life, we come across many objects which are similar kind or in words which are basically same. For example we can think about a car. There are different brands , color, look, style, parts, but basically they all are cars. All them of are made by different companies but with similar kind of components.
We can say all of them are different instances of the class car. They all belongs to the car class. Every instance is known as an object in computer world. A class can contain variables or methods to access those variables.In Python everything is an object. Even if you create an integer, that is an object of the Integer class. In C++ this is different.

11.1. Your first class

Before writing your first class, you should know the syntax. We define a class in the following way..

class nameoftheclass:
    statement1
    statement2
    statement3

in the statements you can write any python statement, you can define functions (which we call methods of a class).

>>> class MyClass:
...     a = 90
...     b = 88
...
>>> p = MyClass()
>>> p
<__main__.MyClass instance at 0xb7c8aa6c>

In the above example you can see first we are declaring a class called MyClass, writing some random statements inside that class. After the class definition, we are creating an object p of the class MyClass.If you do a dir on that...

>>> dir(p)
['__doc__', '__module__', 'a', 'b']

You can see the variables a and b inside it.