Classes in Python
Classes in Python
Advantages of classes
● Classes provide an easy way of keeping the data members and methods
together in one place which helps in keeping the program more organized.
● Using classes also provides inheritance.
● Classes also help in overriding any standard operator.
● Using classes provides the ability to reuse the code which makes the
program more efficient.
● Grouping related functions and keeping them in one place (inside a class)
provides a clean structure to the code which increases the readability of
the program.
Creating class
Instance variable
Object creation
Object calling
_init_ method : Constructors
● The __init__ method act as
constructors in python.
● Constructors are used to initializing
the object’s state.
● Like methods, a constructor also
contains a collection of
statements(i.e. instructions) that are
executed at the time of Object
creation. It runs as soon as an object
of a class is instantiated. The method
is useful to do any initialization you
want to do with your object.
● You can assign values to instance
variables during the object's creation
by passing arguments to the
constructor.
Class variables
Class variables
are the variables
whose single copy
is available to all
instances of the
class
Private
variable and
methods
Private variable
Use double
underscore with
variable
Class methods
Inner Class
Inheritance
Inheritance is the capability of one class to derive or inherit the properties
from another class.
The benefits of inheritance are:
● It represents real-world relationships well.
● It provides reusability of a code.
● it allows us to add more features to a class without modifying it.
● It is transitive in nature, which means that if class B inherits from another
class A, then all the subclasses of B would automatically inherit from class A
Inheritance syntax
constructor in inheritance
In multilevel inheritance,
features of the base class
and the derived class are
inherited into the new
derived class.
Method Resolution Order in Python
Every class in Python is derived from the object class. It is the most base type
in Python. So technically, all other classes, either built-in or user-defined, are
derived classes and all objects are instances of the object class.