0% found this document useful (0 votes)
3 views25 pages

Python Programming Unit III

The document provides an overview of Python classes and objects, explaining their fundamental concepts in object-oriented programming. It covers class definitions, class and object variables, constructors, destructors, and the use of built-in functions to manage class attributes. Additionally, it discusses class methods and static methods, highlighting their differences and use cases.

Uploaded by

23eg106e26
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
3 views25 pages

Python Programming Unit III

The document provides an overview of Python classes and objects, explaining their fundamental concepts in object-oriented programming. It covers class definitions, class and object variables, constructors, destructors, and the use of built-in functions to manage class attributes. Additionally, it discusses class methods and static methods, highlighting their differences and use cases.

Uploaded by

23eg106e26
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 25

Python Classes and Objects

Classes
Classes and objects are the two main aspects of object
oriented programming.
In fact, a class is the basic building block in python
A class creates a new type and object is an instance (or
variable) of the class.
Classes provides a blueprint or a template using which
objects are created.
In fact, in python, everything is an object or an instance of
some class.
All integers variables that we define in our program are
actually instances of class int.
All string variables are objects of class string.
Python Classes and Objects
Classes
We had used string methods using the variable name
followed by the dot operator and the method name.
We can find out the type of any object using the type()
function.
From the syntax we see that class definition is quite similar
to function definition.
It starts with a keyword class followed by the class_name
and a colon(:).
The statement in the definition can be any of these
sequential instructions, decision control statements, loop
statements and can even include function definition.
Variables defined in a class are called class variables.
Function defined in a class are called class methods.
Python Classes and Objects
Classes
Class variables and class methods are together known as
class members.
The class members can be accessed through class objects.
Class methods have access to all the data contained in the
instance of the object.
Class definitions can appear anywhere in a program, but
they are usually written near the beginning of the program,
after the import statements.
When a class definition is entered, a new namespace is
created, and used as the local scope.
Therefore, all assignments to local variables go into this new
namespace.
Python Classes and Objects
Classes
A class creates a new local namespace where all its
attributes(data and functions) are defined.
Once a class is define, the next jbb is to create an object(or
instance) of that class
The object can then access class variables and class
methods using the dot operator(.).
Object_name=class_name()
Creating an object or instance of a class is known as class
instantiation.
To crate a new object, call a class as if it were a function.
For accessing a class member through the class object is
Object_name.class_member_name
Python Classes and Objects
Classes
Syntax:
class class_name:
statement 1
statement 2
Example:
class ABC:
var=10
obj=ABC()
print(obj.var)
OUTPUT:
10
Python Classes and Objects
Classes
Example:
class ABC():
var=10
def display(self):
print(“In class method……”)
obj=ABC()
print(obj.var)
obj.display()
OUTPUT:
10
In class method……..
If you have a method which takes no arguments then you still
have to define the method to have a self argument
Python Classes and Objects
Classes:
Key points to remember:
The statements inside the class definition must be properly
indented.
A class that has no other statements should have a pass
statement at least.
Class methods or functions that begins with double
underscore(__) are special functions with a predifined and a
special meaning.
Python Classes and Objects
Classes:
Constructor:
Example:
The __init__() method is automatically executed when an
object of a class is created.
class ABC():
def __init__(self,val):
print(“In class method…”)
self.val=val
print(“The value is:”,val)
obj=ABC(10)
OUTPUT:
In class method……
The value is : 10
Python Classes and Objects
Classes: Class Variables and Object Variables
If a class has n objects, then there will be n separate copies of
the object variables 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
reflected in other objects.
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 in all other
objects.
Class variables and object variables are ordinary variables that
are bound to the class’s and object’s namespace respectively.
Python Classes and Objects
Classes:
Constructor:
Example:
Class ABC():
class_var=0
def __init__(self,var):
ABC.class_var+=1
self.var=var
print(“The object value is:”,var)
print(“The value of class variable
is:”,ABC.class_var)
Obj1=ABC(10)
Obj2=ABC(20)
Obj3=ABC(30)
Python Classes and Objects
Classes:
Constructor:
OUTPUT:
The object value is: 10
The value of class variable is: 1
The object value is: 20
The value of class variable is: 2
The object value is: 30
The value of class variable is: 3

Note: class variables are usually used to keep a count of


objects created from a class.
Python Classes and Objects
Classes:Destructor:Example:
Class ABC():
class_var=0
def __init__(self,var):
ABC.class_var+=1
self.var=var
print(“The object value is:”,var)
print(“The value of class variable
is:”,ABC.class_var)
def __del__(self):
ABC.class_var-=1
print(“Object with value %d is going out of
scope”%self.var)
Python Classes and Objects
Classes:
Descturctor:
obj1=ABC(10)
obj2=ABC(20)
obj3=ABC(30)
del obj1 del obj2 del ob3
OUTPUT:
The object value is: 10
The value of class variable is: 1
The object value is: 20
The value of class variable is: 2
The object value is: 30
The value of class variable is: 3
Python Classes and Objects
Classes:
Use of class variable or class attributes is to count the
nubmer of objects create.
Use of class variable is to define constants associated with a
particular class or provide default attribute values.
Variable to specify a default value for the objects.
Each individual object may either change it or retain the
default value.
Python Classes and Objects
Classes:Constructor:Example:
class Number:
even=0
def check(self,num):
if(num%2==0):
self.even=1
def even_odd(self,num):
self.check(num)
if(self.even==1):
print(num, “is even”)
else:
print(num, “is odd”)
n=Number()
n.even_odd(21) OUTPUT: 21 is odd
Python Classes and Objects
Classes: Name Clashes: Example:
class Number: overiding means that the first definition is not
even=[] available anymore
odd=[]
def __init__(self,num):
self.num=num
if(num%2==0):
Number.even.append(num)
else:
Number.odd.append(num)
N1=Number(21) N4=Number(54)
N2=Number(32) N5=Number(65) N3=Number(43)
Print(“Even Numbers are:”,Number.even) [32,54]
Print(“Odd Numbers are:”,Number.odd) [21,43,65]
Python Classes and Objects
Classes: Constructor:Example:
class Number: overiding means that the first definition is not
even=[] available anymore
odd=[]
def __init__(self,num):
self.num=num
if(num%2==0):
Number.even.append(num)
else:
Number.odd.append(num)
N1=Number(21) N4=Number(54)
N2=Number(32) N5=Number(65) N3=Number(43)
Print(“Even Numbers are:”,Number.even) [32,54]
Print(“Odd Numbers are:”,Number.odd) [21,43,65]
Python Classes and Objects
Builtin function to check, get, set and delete class attributes
Python has some builtin functions that can also be used to
work with attributes(variables defined in class)
You can use these functions to check whether a class has a
particular attribute or not, get its value if it exists, set a new
value, or even delete that attribute.
hasattr(obj,name): The function is used to check if an
object possesses the attribute or not
getattr(obje,name[,default]): The function is used to access
or get the attribute of object. Since getattr() is a builtin
function and not a method of the class, it is not called usign
the dot operator.
setattr(obje,name,value): The function is used to set an
attribute of the object.if attribute does not exists, then it
would be created.
Python Classes and Objects
Builtin function to check, get, set and delete class attributes
delattr(obje,name): The function deletes an attribute.once
deleted, the variable is no longer a class or object attribute.
Example:
class ABC():
def __init__(self,var):
self.var=var
def display(self):
print(“Var is=“,self.var)
obj=ABC(10)
obj.display()
print(“Check if object has attribute var…”,hasattr(obj,’var’))
getattr(obj,’var’)
setattr(obj,’var’,50)
print(“After setting value, var is :”,obj.var)
setattr(obj,’count’,10)
print(“New variable count is created and its value is”,obj.count)
delattr(obj,’var’)
print(“After deleting the attribute, var is :”obj.var)
Python
Builtin class attributes
Classes and Objects
Every class defined in python has some builtin attributes
associated with it. Like other attributes, these attributes can
also be accessed using dot operator.
.__dict__: The attribute 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 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__: the attribute is used in inheritance to return the
base classes in the order of their occurrence in the base class
list. As for now, it returns an empty tuple.
Python Classes
Builtin class attributes Example:
and Objects
class ABC():
def __init__(self,var1,var2)
self.var1=var1
self.var2=var2
def display(self):
print(“var1 is=“,self.var1)
print(“var2 is=“,self.var2)
obj=ABC(10,12.34)
obj.display()
print(“object.__dict__-”,obj.__dict__)
print(“object.__doc__-”,obj.__doc__)
print(“class.__name__-”,obj.__name__)
print(“object.__module__-”,obj.__module__)
print(“class.__bases__-”,obj.__bases__)
Classes:
Python Classes
Class Methods:
and Objects
Methods define in a class are called by an instance of a
class.
These methods automatically take self as the first
argument.
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 classmethod is cls, not the
slef.
Class methods are widely used for factory methods, which
instantiate an instance of a class, using different parameters
from those usually passed to the class constructor.
Class methods are marked with a classmethod decorator.
(@)
Classes:
Python Classes
Class Methods:
and Objects
Example:
class Rectangle:
def __int__(self,length,breadth):
self.length=length
self.breadth=breadth
def area(self):
return self.length*self.breadth
@classmethod
def Square(cls,side):
return cls(side,side)
S=Rectangle.Square(10)
print("AREA=",S.area())
Classes:
Python Classes
Static Methods:
and Objects
Static methods are a special case of 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 methods does not receive
any additional arguments.
They are just like normal functions that belongs to a class.
A static methods does not use the self variable and is
defined using a builitin function named staticmethod.
Python has a handy syntax, called a decorator, to make it
easier to apply the static method function to the method
function definition.
Classes:
Python Classes
Static Methods:
and Objects
Example:
class choice:
def __init__(self,sujects):
self.subjects=subjects
@staticmethod
def validate_subjects(subjects):
if "CSA" in subjects:
print("This option is no longer available")
else:
return True
subjects=["DS","CSA","Foc","OS","ToC"]
if all(choice.validate_subjects(i) for i in subjects):
ch=choice(subjects)
print("You have been alloted the subjects:",subjects)

You might also like