Classes and Objects in python
Classes and Objects in python:
Contents:
- Programming Paradigms
- What are classes and objects?
- Classes and Objects in programming
- User-defined classes
- Access Convention
- Object Initialization
- Class Variables & Methods
- Var() and dir() function
- More vars() and dir ()
1.Programming Paradigms:
● Paradigm means the principle according to which a program is
organized to carry out a given task.
● Python supports three programming paradigms structured
programming, Functional programming and object-oriented
programming (OOP).
● There are situations when Functional programming is the obvious
choice, and other situations where procedural programming is the
better choice.
● Many languages facilitate programming in one or more paradigm.
For example python supports Functional procedural, Object
oriented and event-driven programming modals.
● Paradigms are not meant to be mutually exclusive. A single
program may be multiple paradigms.
2.What are Classes and Objects?:
● World is object oriented. It is full of objects like Sparrow, Rose,
Guitar, Keyboard, etc.
● Each object is a specific instance of a class. For example,
Sparrow is a specific instance of a bird class or Rose is a specific
instance of a Flower class.
● More examples of classes and objects in real life:
Bird is a class. Sparrow, Crow, Eagle, are objects of bird class.
Player is a class. Sachin, Rahul, Kapil, are objects of player class.
Flower is a class. Rose, lily, Gerbera are objects of Flower class.
Instrument is a class. Sitar, Flute are object of Instrument class.
● A class describes two things the form an object create from it will
take and functionality it will have. For example, a Bird class may
specify the form in term of weight, color, number of feathers, etc.
and functionality in terms of flying, hopping, chirping eating, etc.
● The form is often termed as properties and the functionality is
often termed as methods. A class lets us bundle data and
functionality together.
● When objects like Sparrow or Eagle are created from the bird
class the properties will have values. The method can either
access or manipulate these values. For example, the property
weight will have value 250 grams for a Sparrow, but 10kg for an
Eagle object.
● Thus, class is generic in nature, whereas an object is specific in
nature.
● Multiple objects can be created from a class. The process of
creation of an object from a class is called instantiation.
3. Classes and Objects in programming:
● In python every type is a class. So int, float, complex, bool, str,
list, tuple, set, dict are all classes.
● A class has a name, whereas objects are nameless. Since object of
not have names, they are referred using their addresses in
memory.
● When we use a simple statement num = 10, a nameless object of
Thus, Thus, num refers to or points to the nameless object
containing value 10.
● However, instead of saying that num refers to a nameless int
object, often for sake of convenience, it is said that num is an
int object.
● More programmatic examples of classes and objects:
a = 3.14 # a is an object of float class
s = ' Sudesh ' # s is an object of str class
lst = [10,20,30] # lst is an object of list class
tpl = ('a' , 'b' , 'c, ) # tpl is an object of tuple class
● Different objects of a particular type may contain different data,
but same methods. Consider the code snippet given below.
s1 = ' Rupesh ' #s1 is object of type str
s2 = ' Geeta ' # s2 is object of type str
Here s1 and s2 both are str objects containing different data, but
same methods like upper( ), lower( ), capitalize( ), etc.
● The specific data in an object is often called instance data or
properties of the object or state of the object or attributes of the
object. Methods in an object are called instance methods.
4. User-defined Classes:
● In addition to providing ready-made classes like int, str, list,
tuple, etc. , python permits us to define our own classes and
create objects from them.
● The classes that we define are called user-defined data types.
Rules for defining and using a user-defined class and a standard
class are same.
● Let us define a user-defined class Employee.
class Employee ()
def_data (self, n, a, os) :
self.name = n
self.age = a
self.salary = os
def display_data (self ) :
print( self.name, self.age, self.salary )
e1 = Employee ( )
e1.set_data (" Ramesh " ,23, 25000 )
e1.display_data ( )
e2 = Employee ( )
e2.set_data ( " Suresh ", 25,30000 )
e2.display_data ( )
● The Employee class contains two method set_data ( ) and
display_data ( ) which are used to set and display data present in
objected create from Employee class.
● Two nameless objects gets created through the statements:
e1 = Employee ( )
e2 = Employee ( )
● The syntax to call an objects method is object.method ( ), as in
e1.display_data( ).
● Whenever we call an instance method using a object, address of
the object gets passed to the method implicitly. This address is
collected by the instance method in a variable called self.
● Thus, when e1.set_data (" Ramesh " , 23 , 25000 ) calls the
instance method set_datd ( ), first parameter passed to it is the
address of object, followed by values ' Ramesh ' , 23 , 25000.
● Within set_data ( ) self contain the address of first object.
Likewise, when set_data ( ) is called using e2, self contains
address of the second object.
● Using address of the object present in self we indicate which
object's instance data we wish to work with. To do we prepend
the instance data with self. as in self.name, self.age and
self.salary.
● Self is like this pointer of c++ or this reference of java. In place
of self any other variable name can be used.
5. Access Convention:
● We have accessed instance method set_data ( ) and
display_data ( ) from outside the class. Even instance data name,
age and salary are accessible from outside the class. Thus,
following statement would work:
e3 = Employee ( )
e3.name = " Rakesh "
e3.age = 25
● However, it is a good idea to keep data in a class inaccessible
from outside the class and access it only through member
functions of the class.
● There is no mechanism or keyword available in python to
enforce this. Hence a convention is used to start the instance data
identifiers with two leading underscores (often called underscore,
short for double underscores ). Example: __name, __age and
__salary.
6. Object Initialization:
● There are two way to initialize an object:
Method 1: Using methods like get_data ( ) / set_data ( ).
Method 2: Using special methods __init__( ).
● get_data ( ) can receive data from keyword into instance data
variable. Set_data ( ) can set up instance data with a values that it
receives. The benefit of this method is that the data remains
protected from manipulation from outside the class.
● The benefit of initializing an object using the special method
__init__( ) is that it guarantees initialization, since __init__( ) is
always called when an object is created.
● Following program illustrates both these methods:
class Employee :
def set_data( self, n, a, os) :
self.__name = n
self.__age = a
self.__salary = os
def display_data ( self ):
print(self.__name, __age, self.__salary )
def__init__(self, n =' ', a = 0, os = 0.0 ):
self.__name = n
self.__age = a
self.__salary = os
def__del__(self ):
print(" Deleting object " + str ( self ) )
On execution of this program, we get the following output
e1 = Employee ( )
e1.set_data ( " Suresh " , 25 , 23000 )
e1display_data ( )
e2 = Employee (" Ramesh " , 23 , 25000 )
e2.display_data ( )
e1= None
e2 = None
● The statements
e1 = Employee ( )
e2 = Employee (" Ramesh " , 23, 25000 )
create two objects which are referred by e1 and e2. In both cases
__init__( ) is called.
● Whenever an object is create, space is allocated for it in memory
and __init__( ) is called. So address is passed to __init__( ).
● __init__( )'s parameters can take default values. In our program
they get used while creating object e2.
● __init__( ) doesn't return any value.
● If we do not define__init__( ), then python inserts a default
__init__( ) method in our class.
● __init__( ) is called only once during entire lifetime of an object.
● A class may have__init__( ) as well as set_data ( ).
__init__( )--To initialize object.
set_data ( ) --To modify an already initialized object.
● __del__( ) method gets called automatically when an object goes
out of scope. cleanup activity, if nay, should be done in__del__( ).
● __init__( ) method is similar to constructor function of C++ /
java.
● __del__( ) is similar to destructor function of C++.
7. Class Variable and Methods:
● If we wish to share a variable amongst all the object of a class,
we must declare the variable as a class variable or class
attribute.
● To declare a class variable, we have to create a variable without
prepending it with self.
● Class variable do not become part of object of class.
● Class variable are access using the syntax classname.varname.
● Contrasted with instance method, class methods do not receive a
self argument.
● Class method can be use accessed using the syntax
classname.methodname( ).
● Class variable can be used to count how many objects have been
created from a class.
● Class variable and method are like static members in C++ / java.
8. Vars ( ) and dir ( ) functions:
● There are two useful built-in function vars () and dir ( ). Of
these, vars ( ) returns a dictionary of attributes and their values,
whereas dir ( ) return a list of attributes.
● Given below is the sample usage of these functions:
import math # standard module
import functions # some user-define module
a = 125
s = " Spooked "
print(vars ( ) ) # print dict of attributes in current module.
# including a and s
print(vars (math) ) # print dict of attributes in math module
print(vars(functions)) # print dict of attributes in functions
module
print(dir () ) # print list of attributes in current module
# including a and s
print(dir (math) ) # prints list of attributes in math module
print(dir (function) ) # print list of attributes in functions module
9. More vars ( ) and dir ( ):
● Both the built-in function can be used with a class as well as an
object as shown in the following program.
class fruit:
count = 0
def__init__(self,name =' ', size = 0, color =' '):
self.__name = name
self.__size = size
self.__color = color
fruit.count + =1
def display ( ):
print( fruit.count )
f1 = fruit ( " Banana ", 5, "Yellow" )
print(vars( fruit) )
print(dir (fruit) )
print(vars(f1) )
print(dir (f1) )
On execution of this program, we get the following output:
(... ... ... , 'count': 0,'__init__': <function fruit.__init___>,
'display'; <function fruit.display at 0x7f290a00f598>, ... .... ...)
[... ... .. '__init__', 'count ', 'display ' ]
{'_name' : ' Banana ', '_size ': 5, '_color ' : ' Yellow ' }
[... ... ... '__init__', '_color ', '_name ', '_size ', ' count ', ' display ']
● When used with class, vars ( ) return a dictionary of the class's
attributes and their vales. On the other hand the dir ( ) function
merely returns a list of its attributes.
● When used with object, vars ( ) returns a dictionary of the
object's attributes and their values. In addition, it also returns the
object's class's attributes, and recursively the attributes of its
class's base classes.
● When used with object, dir ( ) returns a list of the object's
attributes, object's class's attributes, and recursively and
recursively the attributes of its class's base classes.
Classes and Objects in python
Reviewed by For Learnig
on
May 26, 2023
Rating:
No comments:
If you have any doubts, please tell me know