You are on page 1of 20

Advanced Python OOP

Programming
IUST 92
MOHAMMAD REZA BARAZESH

Python has a dynamic structure


U can change or delete anything in a class in runtime

& u can access the members of classs itself

Class dictionary
U can access a class dictionary with the function vars ()

Or we can access it via the __dict__ member of the class :

We can make changes to the class itself by changing its dictionary

New style classes


all classes must be set to have an object instance as their parent

Static methods in python

Inheritance

The subclass will have all the members of the super


classes .
If the subclass has a method with the same name in the
superclass , it will override it .

Inheritance II
We still can call an overridden super class method :

Public private - protected


Public XXXX
Private __XXXX
Protected _XXXX
Use private to force the using of setter and getter

public
The type or member can be accessed by any other code in the same assembly or another
assembly that references it.
private
The type or member can only be accessed by code in the same class.
protected
The type or member can only be accessed by code in the same class or in a derived class.

Special methods
__init__
How to have multiple constructors ?

Python calls
def __init__(self, *args, **kwargs):
#args -- tuple of anonymous arguments
#kwargs -- dictionary of named arguments

A note :
We can change a mutable object inside an immutable one !
So we can actually make any changes to any mutable object inside a
*args tuple .

Special methods
__del__ :
Is called when a member is no longer referenced .
What is a reference in python ?
Everything in python is passed by reference . We just have to keep in
mind whether the object is mutable or not .
Every time we use the = operator we are making a new reference to
our desired object .

Special methods
__str__ & __repr__
If the __str__ is not available the latter will get executed .
Please keep in mind that the returned value of this methods must be
in string form .

Special methods
__setattr__

Special methods
__getattr__ :

Operator overloading
Make sure to return in an instance of the class if needed .
( why ??)

Classes docstrings
Always add doc strings to your classes .
Doc strings can later be turned into API documentions using third
party modules .

Adding a method to our class in runtime

Adding a method to an instance in runtime

Python decorators
The @ symbol applies a decorator to a function
This is equal of saying :
>>> add = wrapper(add)

A sample : using decorators to create a static method .

You might also like