[go: up one dir, main page]

0% found this document useful (0 votes)
4 views24 pages

Classes and Objects

The document provides an overview of Python's object-oriented programming, focusing on classes and objects, their creation, and the use of instance and class variables. It explains the role of the __init__() constructor method, the importance of public and private data members, and includes examples demonstrating class methods and magic methods. The document emphasizes the distinction between class and instance variables, highlighting design considerations in their usage.

Uploaded by

Naraiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views24 pages

Classes and Objects

The document provides an overview of Python's object-oriented programming, focusing on classes and objects, their creation, and the use of instance and class variables. It explains the role of the __init__() constructor method, the importance of public and private data members, and includes examples demonstrating class methods and magic methods. The document emphasizes the distinction between class and instance variables, highlighting design considerations in their usage.

Uploaded by

Naraiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Python Programming

Language
Classes and Objects
• Python is an “object-oriented programming language” This means that almost all the
code is implemented using a special construct called classes.
• In object-oriented programming you write classes that represent real-world things and
situations, and you create objects based on these classes.
• Programmers use classes to keep related things together. Classes provide means for
building data and functionality together. This is done using the keyword “class”.
• Creating a new class creates a new data type, which allows new instances (i.e.
objects) of that type to be created.
• A Class acts as a blueprint or a template for creating objects. An Object is an
instance of a Class. Objects have member variables and have behavior associated
with them.
• Each class instance (i.e object) can have attributes attached to it for maintaining its
state.
• Class instances can also have methods(defined by its class) for modifying its state.
• Every instance of a class can be identified uniquely, i.e. objects have their own
identity.
• Multiple names/references can be bound to same object.
Classes in Python
• Syntax for defining a class:
class Class_name:
<statement 1>
<statement 2>
.
.
.
<statement n>
• A class creates a new local namespace where all its attributes are defined.
• Example: create a simple, empty class with no functionalities.
>>> class animal:
... pass
...

>>> type(animal)
<class 'type'>
3
Creating Objects
• In Python, everything is an object or an instance of some class.
• An object is created by invoking the constructor of the class. This object will
then be called the instance of the class. Creating an object or instance of a
class is known as class instantiation.
• Syntax:

object_name=class_name()
• Example:
>>> dog = animal()

>>> type(dog)
<class '__main__.animal’>

>>> print(dog)
4
<__main__.animal object at 0x00E98160>
Creating Objects
>>> cat=animal()
>>> type(cat)
<class '__main__.animal’>
>>> print(cat)
<__main__.animal object at 0x00E98280>

>>> pug=dog
>>> type(pug)
<class '__main__.animal'>
>>> print(pug)
<__main__.animal object at 0x00E98160>

>>> id(dog)
15303008

>>> id(cat)
15303296

>>> id(pug)
15303008
5
Class attributes, methods and self argument
• 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. Those functions are called methods.
• Class methods are exactly same as ordinary functions that we have
been defining. When you define methods, you will need to always
provide the first argument to the method with a self keyword.
• The self argument refers to the object itself. That is the object that
has called method.
• Syntax for accessing a class member through the class object is :
object_name.class_member_name

6
attributes, methods and self argument
Example 1:

class Animal():
legs=0 #class variable
def display(self):
print("This animal has ",self.legs," legs")

obj = Animal()
obj.display()

dog=Animal()
dog.legs=4 #instance variable
dog.display()

emu=Animal()
7
emu.legs=2 #instance variable
emu.display()
Example 2:

class Animal():
def setLegs(self, legs):
self.legs=legs
def display(self):
print("This animal has ",self.legs," legs")

obj = Animal()
obj.setLegs(0)
obj.display()

dog=Animal()
dog.setLegs(4)
dog.display()

emu=Animal()
8
emu.setLegs(2)
emu.display()
Example 3:

class Animal():
def setName(self,name):
self.name=name
def setLegs(self, legs):
self.legs=legs
def display(self):
print(self.name," has ",self.legs," legs")

obj = Animal()
obj.setName("generic")
obj.setLegs(0)
obj.display()

dog=Animal()
dog.setName("dog")
dog.setLegs(4)
dog.display()

emu=Animal()
emu.setName("emu")
emu.setLegs(2)
emu.display()
9
When you write a class, you define the general behavior that a whole category of objects can have.
When you create individual objects from the class, each object is automatically equipped with the general
behavior; you can then give each object whatever unique traits you desire using instance variables.
The __init__() method (the class constructor)
• The task of constructors is to initialize(assign values) to the data members of the
class when an object of class is created.
• In Python the __init__() method is called the constructor.
• The __init__() method is automatically invoked when an object of a class is
created.
• This method is useful to initialize the variable of the class object.
Example:
class Snake():
def __init__(self,name):
self.name=name
def setName(self, name):
self.name=name

snake = Snake("python")
print(snake.name)
snake.setName("anaconda") 10
print(snake.name)
Example 2:
class Snake():
def __init__(self, name):
self.name=name
def setName(self, name):
self.name=name

snake = Snake("python")
print(snake.name, id(snake))

snake.setName("anaconda")
print(snake.name, id(snake))

snake = Snake("anaconda")
print(snake.name, id(snake))
11
Class objects and Instance objects
Class variables are owned by class and instance variables are owned by each object.

Instance Objects:
• If a class has ‘n’ objects, then there will be n separate copies of the instance variable
because - each object will have its own instance variable.
• The instance variable is not shared between objects.
• A change made to the instance variable by one object/instance will not be reflected in
other objects.
• There can be zero or more instances/objects.
• It is mandatory to instantiate a class to get an instance or an object.
• The instance/object can be given a name when the class is being instantiated.
• instance variables can only be accessed after creating an instance of class.

12
Class objects and Instance objects
Class objects:
• There can be only once class object per class.
• If a class has one class variable, then there will be one copy only for that variable.
• All the instances or objects of that class will share the class variable in common.
• 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.
• variables and methods of Class Object can be accessed by using
ClassName.variable_name
ClassName.method_name

13
Example:
class Test():
c_var=10 #class variable
def __init__(self,var):
Test.c_var+=1
self.var=var
print("The instance variable value is :",var)
print("The value of class variable is :",Test.c_var)
obj1=Test(10)
obj2=Test(20)
obj3=Test(30)

14
Public and private data members
• Public variables are those that are defined in the class and can be accessed from
anywhere in the program using the dot operator.
• Private variables are those 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.
• But if for some reason, if we need to do it, then syntax is:
objectname._classname__privatevariable

15
Example:
class Test():
def __init__(self,var1,var2):
self.var1=var1
self.__var2=var2
def __display(self):
print("from class method, var1=",self.var1)
print("from class method, var2=",self.__var2)
obj=Test(10,20)
obj._Test__display() #obj.display()
print("From main module, var1=",obj.var1)
print("From main module, var1=",obj._Test__var2)
#print("From main module, var1=",obj.var2)

16
Program modifying a mutable type
attribute
class Number:
evens=[ ]
odds=[ ]
def __init__(self,num):
self.num=num
if (self.num)%2==0:
Number.evens.append(self.num)
else:
Number.odds.append(self.num)
N1=Number(21)
N2=Number(32)
N3=Number(43)
N4=Number(54)
N5=Number(65)
print("Even Numbers are :",Number.evens)
print("Odd Numbers are :",Number.odds)
17
Without using instance variable
class Number:
evens=[ ]
odds=[ ]
def __init__(self,num):
if num%2==0:
Number.evens.append(num)
else:
Number.odds.append(num)
N1=Number(21)
N2=Number(32)
N3=Number(43)
N4=Number(54)
N5=Number(65)
print("Even Numbers are :",Number.evens)
print("Odd Numbers are :",Number.odds)

18
Design issues – class vs instance variables
class Dog:
tricks = [] # mistaken use of a class variable
def __init__(self, name):
self.name = name

def add_trick(self, trick):


self.tricks.append(trick)
#Dog.tricks.append(trick)- this works same as the above stmt

d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('fetch ball')
print(d.tricks) # unexpectedly shared by all dogs
print(e.tricks)

19
Correct design of the class should use an
instance variable instead:
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each
dog

def add_trick(self, trick):


self.tricks.append(trick)

d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('fetch ball')
print(d.tricks)
print(e.tricks)

20
Some built-in class methods(Magic methods)
Magic methods in Python are the special built-in methods which add "magic" to
your class. Magic methods are not meant to be invoked directly by you, but the
invocation happens internally from the class on a certain action.

• __repr__(): it returns a string representation of an object. Works only


on an object, not just class instance.
• __str__(): used to print a readable string presentation of your object
• __cmp__(): compare any two python objects # obsolete in python3
• __len__(): returns the length of an object.
• __getitem__(): used for indexing
• __setitem__(): used to assign an item to indexed values.
• __iter__(): used for iteration over objects.
• __lt__(), __le__(), __eq__(), __gt__(), __ge__() :
used to compare two objects.
21
Example-1:
class Complex:

# Constructor
def __init__(self, real, imag):
self.real = real
self.imag = imag

# For call to repr(). Prints object's information


def __repr__(self):
return 'Rational(%s, %s)' % (self.real, self.imag)

# For call to str(). Prints readable form


def __str__(self):
return '%s + i%s' % (self.real, self.imag)

t = Complex(10, 20)
print(repr(t))
print(str(t)) #same as print(t)

22
Example-2:
class Test():
def __init__(self,name,var):
self.name=name
self.var=var
def __repr__(self):
return repr(self.var)
def __len__(self):
return len(self.name)
def __cmp__(self,obj):
return (self.var)-(obj.var)
obj=Test("abc",10)
print("The value stored in object is :",obj) #invokes __repr__
print("length=",len(obj)) # invokes __len__
obj1=Test("x",1)
print(obj==obj1) # invokes __cmp__ , also invoked by obj!=obj1
val=obj.__cmp__(obj1)
if(val==0):
print("equal")
elif (val==-1):
print("first value is less than second")
23
else:
print("second value is less than first")
Example-3:
class Numbers:
def __init__(self,mylist):
self.mylist=mylist
def __getitem__(self,index):
return self.mylist[index]
def __setitem__(self,index,val):
self.mylist[index]=val
numlist=Numbers([1,2,3,4,5,6,7,8,9])
print(numlist[5])
numlist[3]=10
print(numlist.mylist)
24

You might also like