Tutorial Python Classes

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Here is Python class named “Person” (by convention usually CamelCase starting with uppercase) and created an instance of that class called “john” …

In line 2, you have a class method declared with a decorator. Note how it takes in a “cls” and use that inside the method.

In line 25 you have an instance method. The first param is always “self”. But when calling, you don’t put it as argument as you can see in line 29 and 30.

Line 20 is the special initializer __init__ and is called in line 29. It creates an instance of the class.

Line 19 and 13 are setter and getter respectively. The underscore preceding the variable is only a convention to indicate to other developers that variable is intended to be private — kind of like semi-private. But there is no enforcement of “private” in Python. If you use double underscore preceding the variable (and no double underscore after), then Python will “name mangle” the variable making is “more private”. For example, we change to double underscore for self.__age and it works as before…

When you print out the instance of a class like …

print(john)

You get something like …

<main.Person object at 0x013B0A50>

You can customize this output by override the __repr__ method like this …

Python inheritance

Now the Student class inherits from Person class.
It need not over-ride the initializer, which it then will just use the parent’s initializer. However, we will have the Student class over-ride the __init__ with the additional param of “school”. In that initializer, we can access the parent with super() …

Python support multiple inheritance and the order of inheritance matters as determined by the “Method Resolution Order”. To see this …

print(Student.mro())
print(Student.__mro__)
help(Student)


Related Posts

Tags

Share This