Programming and Problem Solving Lecture - 15-Classes and Objects
Programming and Problem Solving Lecture - 15-Classes and Objects
Prepared By :
Pallavi S Joshi
BOOKS AND REFERENCES
BOOKS AND REFERENCES
Text Book:
Syntax:
Creating Objects
• Once a class is defined, the next job is to create an object (or instance) of that class.
• The object can then access class variables and class methods using the dot operator (.).
• The syntax to create an object is given as,
• Classes provide methods to the outside world to provide the functionality of the object
or to manipulate the object's data.
• Any entity outside the world does not know about the implementation details of the
class or that method.
• Data encapsulation, also called data hiding organizes the data and methods into a
structure that prevents data access by any function (or method) that is not specified in
the class. This ensures the integrity of the data contained in the object.
Data Abstraction and Hiding through Classes
• Encapsulation defines different access levels for data variables and member functions
of the class.
• These access levels specifies the access rights for example, Any data or function with
access level public can be accessed by any function belonging to any class.
• This is the lowest level of data protection.
• Any data or function with access level private can be accessed only by the class in
which it is declared. This is the highest level of data protection.
11
Class Method And Self Argument
• Class methods (or functions defined in the class) are exactly same as ordinary functions
that we have been defining so far with just one small difference.
• Class methods must have the first argument named as self. This is the first argument
that is added to the beginning of the parameter list.
• Moreover, you do not pass a value for this parameter when you call the method.
• Python provides its value automatically. The self argument refers to the object itself.
That is, the object that has called the method.
• This means that even if a method that takes no arguments, should be defined to accept
the self.
• Similarly, a function defined to accept one parameter will actually take two- self and
Class Method And Self Argument
• Since, the class methods uses self, they require an object or instance of the class to be
used. For this reason, they are often referred to as instance methods.
The __init__() Method (The Class Constructor)
• The __init__() method has a special significance in Python classes. The __init__()
method is automatically executed when an object of a class is created.
• The method is useful to initialize the variables of the class object. Note the __init__() is
prefixed as well as suffixed by double underscores.
Class Variables And Object Variables
• Basically, these variables are of two types- class variables and object
variables.
• Class variables are owned by the class and object variables are owned
by each object. What this specifically means can be understood using
following points.
• If a class has n objects, then there will be n separate copies of the
object variable as each object will have its own object variable.
• The object variable is not shared between objects.
• A change made to the object variable by one object will not be
• If a class has one class variable, then there will be one copy only for that
variable. All the objects of that class will share the class variable.
• Since there exists a single copy of the class variable, any change made to
the class variable by an object will be reflected to all other objects.
16
Class Variables And Object Variables - Example
The __del__() Method
• Public variables are those variables that are defined in the class and can
be accessed from anywhere in the program, of course using the dot
operator.
• Private variables, on the other hand, are those variables that are defined
in the class with a double score prefix (__).
• These variables can be accessed only from within the class and from
nowhere outside the class.
Public and Private Data Members-Example
Private Methods
• Like private attributes, you can even have private methods in your class.
• Usually, we keep those methods as private which have implementation details.
• So like private attributes, you should also not use private method from anywhere
outside the class.
• However, if it is very necessary to access them from outside the class, then they are
accessed with a small difference.
• A private method can be accessed using the object name as well as the class name from
outside the class. The syntax for accessing the private method in such a case would be.
objectname._classname__privatemethodname
Private Methods-Example
Calling a Class Method from Another Class Method
27
Built-in Functions To Check, Get, Set And Delete Class Attributes
• getattr(obj, name[, default]): The function is used to access or get the attribute of
object.
• Since getattr() is a built-in function and not a method of the class, it is not called
using the dot operator. Rather, it takes the object as its first parameter. The second
parameter is the name of the variable as a string, and the optional third parameter
is the default value to be returned if the attribute does not exist.
• If the attribute name does not exist in the object's namespace and the default value
is also not specified, then an exception will be raised.
• Note that, getattr(obj, 'var') is same as writing obj.var. However, you should always
try to use the latter variant.
• setattr(obj,name,value): The function is used to set an attribute of the
object.
• If attribute does not exist, then it would be created.
• The first parameter of the setattr() function is the object, the second
parameter is the name of the attribute and the third is the new value
for the specified attribute.
30
Built-in Functions - Example
Built-in Functions - Example
Built-in Class Attributes
.__dict__: The attributes gives a dictionary containing the class's or object's (with
whichever it is accessed) namespace.
.__doc__: The attribute gives the class documentation string if specified. In case the
documentation string is not specified, then the attribute returns None.
.__name__: The attribute returns the name of the class.
.__module__: The attribute gives the name of the module in which the class (or the
object) is defined.
.__bases__: Used in inheritance to return the base classes in the order of their
occurrence in the base class list.
Built-in Class Attributes
Garbage Collection (Destroying Objects)
38
1) Instance Method: Instance methods are the method which act upon the instance variables of the
class. Instance methods are bound to instances and hence called as : instancename.method().
class student:
def __init__(self,m1,m2,m3):
self.m1=m1
self.m2=m2
self.m3=m3
def avg(self):
return (self.m1+self.m2+self.m3)/3
s1=student(12,22,22)
s2=student(22,44,33)
print(s1.avg())
print(s2.avg())
39
Class Methods
• Class methods are little different from these ordinary methods. First,
they are called by a class (not by instance of the class). Second, the first
argument of the class method is class not the self.
• Class methods are widely used for factory methods, which instantiate
an instance of a class, using different parameters than those usually
passed to the class constructor.
# Python program to understand classmethod
class Subject:
# creating a variable
favorite_subject = "Networking"
# creating a function
def favorite_subject_name(obj):
print("My favorite_subject_name is : ", obj.favorite_subject)
Subject.favorite_subject_name()
Static Methods
• Any functionality that belongs to a class, but that does not require the object is placed in the static method. Static
methods are similar to class methods.
• The only difference is that a static method does not receive any additional arguments. They are just like normal
functions that belong to a class.
• A static method does not use the self variable and is defined using a built-in function named static method. Python
has a handy syntax, called a decorator, to make it easier to apply the static method function to the method function
definition.
• The syntax for using the static method decorator.
class Math ():
@staticmethod
def Multiply(one, two):
return one * two
math = Math()
if(12*72 == math.Multiply(12, 72)):
print("Equal")
else:
print("Not Equal")
43