PYTHON
CLASSES & OBJECTS
LECTURE - 08 Dr. Noor Felemban
© Dr. Irfan, Dr. Nida
CLASSES & OBJECTS
• Python is an “object-oriented programming language”
WHAT IS A CLASS?
• A class is a code template for creating objects
• Objects have member variables and have behaviour associated
with them
• In python a class is created by the keyword class
• An object is created using the constructor of the class
• Objects are called the instance of the class
CLASSES & OBJECTS
Create a Class
• To create a class, use the keyword class
Create Object
• Create an object named p1, and print the value of x
OOPS – ATTRIBUTES AND METHODS
• A class by itself is of no use unless there is some functionality
associated with it.
• Functionalities are defined by setting attributes, which act as
containers for data and functions related to those attributes
(called methods).
Attributes Class Object
• Class variable to hold data.
OOPS – ATTRIBUTES AND METHODS
Methods
• You can access class-
variables directly OR you
can define functions (i.e.,
methods) to access them
• When you define
methods, you will need to
always provide the first
argument to the method
with a self keyword.
OOPS – ATTRIBUTES AND METHODS
Class Attributes
• You can also define class level
variables in a method by using
self.variables
• Variables “name” and “salary”
are defined inside __init__ as
a class member variables
OOPS – SELF
Self
• This is similar to this pointer in C++
and this reference in Java.
• When we call a method of object
as myobject.method(arg1, arg2)
• It is automatically converted by
Python into MyClass.method(myobject,
arg1, arg2)
• myobject refer to Self argument.
OOPS – SELF
Self
• You can use any name instead of self, but it has to be the first
parameter of any function in the class
• Use the words mysillyobject and abc instead of self
The first argument is
considered as a self.
OOPS – __INIT__() FUNCTION
The __init__() Function
• __init__() are called constructor in C++,
Java
• All classes have a function called
__init__(), which is always executed
when the class is being initiated.
• Use the __init__() function to assign
values to object properties, or other
operations that are necessary to do
when the object is being created:
OOPS – __INIT__() FUNCTION
Instance attributes and
__init__() method
• You can change attribute
values at runtime.
• This is done by defining the
attributes inside the
__init__() method.
• __init__() is kind of class
constructor()
OOPS – __DOC__ FUNCTION
__doc__ print docstr of
the class.
• The class has a
documentation string, which
can be accessed via
ClassName.__doc__
OOPS – ACCESSING ATTRIBUTES
Accessing Attributes
• We can access class member
variables (attributes) directly or via
methods.
• Access the object's attributes using the
dot operator with object.
• Class variable would be accessed
using class name.
OOPS – ADD ATTRIBUTES
Access Class Attributes
• Class attribute are accessed via Class
Name, i.e. CLASS_NAME.VARIABLE
Add Attributes
• We can add attribute to the object
after creating them.
• The newly added attribute will not
be added to the other object of
similar class.
OOPS – ADD | DEL | MODIFY ATTRIBUTES
We can add, remove, or modify attributes of classes and objects
at any time −
• emp1.age = 7 # Add an 'age' attribute.
• emp1.age = 8 # Modify 'age' attribute.
• del emp1.age # Delete 'age' attribute.
OOPS – ADD | DEL | MODIFY ATTRIBUTES
Instead of using the normal statements to access attributes, you can use the following
functions
• getattr(obj, name[, default]) − to access the attribute of object.
• hasattr(obj,name) − to check if an attribute exists or not.
• setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it
would be created.
• delattr(obj, name) − to delete an attribute.
• Example:
• hasattr(emp1, 'age') # Returns true if 'age' attribute exists
• getattr(emp1, 'age') # Returns value of 'age' attribute
• setattr(emp1, 'age', 8) # Set attribute 'age' at 8
• delattr(empl, 'age') # Delete attribute 'age'
OOPS – BUILT-IN CLASS ATTRIBUTES
Every Python class keeps following built-in attributes and they can
be accessed using dot operator like any other attribute −
• __dict__ − Dictionary containing the class's namespace.
• __doc__ − Class documentation string or none, if undefined.
• __name__ − Class name.
• __module__ − Module name in which the class is defined. This
attribute is "__main__" in interactive mode.
• __bases__ − A possibly empty tuple containing the base classes,
in the order of their occurrence in the base class list.
OOPS – BUILT-IN
CLASS ATTRIBUTES
OOPS – DESTROYING OBJECTS (GARBAGE COLLECTION)
• Python deletes unneeded objects (built-in types or class instances)
automatically to free the memory
• The process by which Python periodically reclaims blocks of memory
that’s no longer are in use is termed Garbage Collection
• Python's garbage collector runs during program execution and is
triggered when an object's reference count reaches zero
• An object's reference count changes as the number of aliases that point
to it changes
OOPS – DESTROYING OBJECTS (GARBAGE COLLECTION)
• An object's reference count increases when it is assigned a new name
or placed in a container (list, tuple, or dictionary).
• The object's reference count decreases when it's deleted with del, its
reference is reassigned, or its reference goes out of scope.
• When an object's reference count reaches zero, Python collects it
automatically.
40 are treated as
object in Python
OOPS – DESTROYING OBJECTS (GARBAGE COLLECTION)
• You normally will not notice when the
garbage collector destroys an orphaned
instance and reclaims its space.
• But a class can implement the special
method __del__(), called a destructor, that
is invoked when the instance is about to be
destroyed.
• This method might be used to clean up any
non memory resources used by an instance.
Example
• __del__() destructor prints the class name
of an instance that is about to be
destroyed
OOPS – CLASS INHERITANCE
• We can create a class by deriving it from a pre-existing class by listing the
parent class in parentheses after the new class name.
• The child class inherits the attributes of its parent class, and you can use
those attributes as if they were defined in the child class.
• A child class can also override data members and methods from the parent.
Syntax
• Derived classes are declared much like their parent class; however, a list of
base classes to inherit from is given after the class name −
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
OOPS – CLASS INHERITANCE
• Create a class named Person, with firstname and lastname
properties, and a printname method
CREATE A CHILD CLASS
Create a class named Student,
which will inherit the properties
and methods from the Person
class:
OOPS – CLASS INHERITANCE
• Use the Student class to
create an object, and
then execute the
printname method:
OOPS – CLASS INHERITANCE – (__INIT__() FUNCTION)
• __init__() function to the child class to initialize the object
• The __init__() function is called automatically every time the class is
being used to create a new object.
• When you add the __init__() function, the child class will no longer
inherit the parent's __init__() function. The child's __init__() function
overrides the inheritance of the parent's __init__() function.
• To keep the inheritance of the
parent's __init__() function,
add a call to the parent's
__init__() function
OOPS – CLASS INHERITANCE – (SUPER() FUNCTION)
• Python also has a super() function that will make the child class inherit
all the methods and properties from its parent
• With super() function, we do not have to use the name of the parent
element, it will automatically inherit the methods and properties from
its parent.
OOPS – CLASS INHERITANCE – [ADD PROPERTIES]
• We can add attribute (class variables, i.e., properties) to a class
OOPS – CLASS INHERITANCE – [ADD METHODS]
• We can also add methods to a class
OOPS – METHOD OVERRIDING
• Method overriding is a concept of OOP that allows us to change the
implementation of a function in the child class that is defined in the
parent class.
• Following conditions must be met for overriding a function:
• Inheritance should be there. Function overriding cannot be done within a class. We
need to derive a child class from a parent class.
• The function that is redefined in the child class should have the same signature as
in the parent class i.e. same number of parameters.
OOPS – METHOD OVERRIDING
Sr.No. Method, Description & Sample Call
__init__ ( self [,args...] )
BASE OVERRIDING 1
Constructor (with any optional arguments)
METHODS Sample Call : obj = className(args)
• Lists of some generic __del__( self )
functionality that you can 2 Destructor, deletes an object
Sample Call : del obj
override in your own classes
__repr__( self )
3 Evaluable string representation
Sample Call : repr(obj)
__str__( self )
4 Printable string representation
Sample Call : str(obj)
__cmp__ ( self, x )
5 Object comparison
Sample Call : cmp(obj, x)
OOPS – POLYMORPHISM
• Polymorphism is a concept of OOP, which means multiple forms.
• Polymorphism enables using a single interface with input of different
datatypes, different class or may be for different number of inputs.
• In this case the function len() is polymorphic as it is taking string as input
in the first case and is taking list as input in the second case.
• Method overriding is a type of polymorphism in which a child class
override the method of the parent class as per its own requirements.
OOPS – DEFINING POLYMORPHIC CLASSES
• Imagine a different class for shapes like Square, Triangle etc.
• We want to calculate the area of that shape. Each shape has a
different number of dimensions which are used to calculate the area of
the respective shape.
METHOD OVERLOADING
• Method or function overloading is a type of polymorphism where
multiple methods with the same name but with a different number or
types of parameters are defined.
• Python doesn't support method overloading with different number of parameters
in functions.
OOPS – DEFINING POLYMORPHIC CLASSES
SOLUTION-1: SOLUTION-2:
Change name of functions to
To define methods with different names calculate_area() in each class.
to calculate the area of the given
shapes. Function overloading behavior
The problem here
is to remember the
name of functions.
OOPS – DEFINING POLYMORPHIC CLASSES
SOLUTION-1: POLYMORPHISM WITH SOLUTION-2: POLYMORPHISM
CLASS METHODS WITH FUNCTIONS
We can use FOR loop to We can also create a function which
iterates over a tuple of objects takes an object as input and then calls
of various shapes and call the function to calculate area
functions.
DATA HIDING – PYTHON ACCESS MODIFIERS
• Most of the languages use three types of access modifiers, they are -
private, public and protected
• Python makes the use of underscores ( _ ) to specify the access
modifier for a specific data member and member function in a class
The members declared as Public are accessible from outside the Class
Access Modifier: Public through an object of the class.
The members declared as Protected are accessible from outside the
Access Modifier: Protected class but only in a class derived from it, i.e. the child or subclass
Access Modifier: Private These members are only accessible from within the class. No outside
Access is allowed
DATA HIDING – PYTHON ACCESS MODIFIERS
Access Modifier: Public
By default, all the
variables and member
functions of a class are
public in a python
program. All the member variables of the class in
the above code will be by default public,
hence we can access them as follows
DATA HIDING – PYTHON ACCESS MODIFIERS
Access Modifier: Protected
According to Python convention adding a prefix
_ (single underscore) to a variable name makes
it protected.
Similarly if there is a child class extending Use an _(underscore) as
the class Employee then it can also access the a prefix to access class
protected member variables of the class protected variables
Employee.
To access protected
member variable of
class Employee from the
class HR:
class Emp:
def __init__(self, name,
sal):
self.__name
= name
self.__sal =
sal
emp = Emp("Irfan", 2000)
DATA HIDING – PYTHON ACCESS MODIFIERS
print(emp._Emp__sal)
print(emp.__sal)
Access Modifier: Private
While the addition of prefix
__(double underscore) results
in a member variable or
function becoming private.
If we want to access the
private member variable, we
will get an error.
DATA HIDING
COMPLETE EXAMPLE
STATIC VARIABLES AND METHODS
• Defining static variable and method is a common programming concept
in many programming languages for creating class variables and
methods.
• In Python, there is no special keyword for creating static variables and
methods.
• Python follows a different but simple approach for defining static
variables and methods.
STATIC VARIABLES AND METHODS
CLASS OR STATIC VARIABLES
• Class or Static variables are the variables that belong to the class
and not to objects.
• Class or Static variables are shared amongst objects of the class.
• All variables which are assigned a value in the class declaration are class
variables.
• And variables which are assigned values inside class methods are instance
variables.
STATIC VARIABLES AND METHODS
STATIC METHODS IN PYTHON
• Static methods are methods which are bound to the class, not to
object of the class
• To call a static method we don't need any class object it can be
directly called using the class name.
• As static methods are bound to the class hence, they cannot change
the state of an object.
STATIC VARIABLES AND METHODS
• In python there are two ways of defining a static method:
STATIC METHOD USING STATICMETHOD() STATIC METHOD USING @STATICMETHOD
Using @staticmethod is a more modern approach of
defining static method
Create info method as static method outside the class
using the staticmethod() and to call info() directly using
the class Shape.
READING
https://www.geeksforgeeks.org/g-fact-34-class-or-static-variables-in-python/
https://www.programiz.com/python-programming/methods/built-in/staticmethod
CLASS DECORATOR
• Decorators allows us to modify the
behavior of function or class.
• It allow us to wrap another function in order to
extend the behavior of the wrapped function,
without permanently modifying it.
• We can make a class as a decorator.
• We have to use a __call__ method of classes.
• To create a class object that acts as a function
then function decorator needs to return an
object that acts like a function, so __call__ can
be useful.
CLASS DECORATOR – EXAMPLE
END OF LECTURE - 08
Dr. Irfan Ullah Khan
© Dr. Irfan, Dr. Nida