Lecture - 08 - Classes and Objects
Lecture - 08 - Classes and Objects
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
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
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.
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
• 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:
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