Classes and Objects Concepts in Python

By
Python classes and objects

Python is an object oriented programming language .Every things in python treated as an object.python supports structured as well as object oriented programming language paradigms.

  • A class contains data and  methods that can access or manipulate this data.Thus a class is a collection of data and methods.A class is a blueprint (prototype) of an object. Thus a class lets us bundle data and functionality together.
  • A user-defined blueprint/prototype for an object is known as class.example : House is an object where blueprint/prototype/model of house is known as a Class.
  • A class is generic in nature,whereas an object is specific in nature.
  • We can create many objects from one class.We can easily access the class member with the help of these objects.
  • An object is also an instance of a class The process of creating this object  is called instantiation
  • We can  also create our own classes.These are often called user defined data types but we generally uses ready-made classes in python.
Example of real life of classes and objects:-

  • Player is a class whereas Sachin ,Rahul,Virat,Kapil dev etc. are the objects of the Player class.
  • Bird is a class whereas eagle,parrot,crow etc. are the objects of the Bird class.
Programmatic example of classes and objects:-
a=5           # a is an object of int class. 

b="Ram"   # b is an object of  string class

ls=[10,20,30,40,50]  #ls is an object of List class

Note:- Here int,float,str etc. are the ready-made classes in python. 

Public and private members:

  • The members of a class (data and methods) are accessible from outside the class.The members of the class should be public.
  • If the members of the class is private ,we can not access the class data from the outside.We can access it through member functions of the class.
  • The private members by convention start with an underscore,as in _id,_name,_age etc.
Before Reading classes and objects,you have to learn function/method concepts first.You can learn it from below link.

Creating classes and objects in python:-

In python, a class is created with the help of class keyword.The syntax to create a class is given below:-

Syntax

class  class_name :

............................statements.............................

The First string inside the class is called documentation string .Each class is associated with a documentation string .Which can be accessed by using class_name.__doc__ This gives us the doc string of that class. 

 e.g.

class student:
    "This is MNT LAB YouTube channel Tutorials..."
    def set_data(self,a,b,c):
        self._name=a
        self._age=b
        self._salary=c
    def show_data(self):
        print(self._name)
        print(self._age)
        print(self._salary)      
    def get_data(sss):
       print(sss._name,sss._age,sss._salary)  
    def display():
      print("Self word is optional,you can use other word(sss)instead self.It is conventionally used in python")   
#creating the instance/object of the class
s1=student()
s1.set_data('Ram',30,20000)
s1.show_data()
print("")
#creating the instance/object of the class
s2=student()
s2.set_data('shayam',20,24000)
s2.show_data()
print("")
s2.get_data()
print("")
#Access the data without object
student.display()
print("")
student.get_data(s1)
#printing the documentation string of the class
print(student.__doc__)
Output:-
Ram
30
20000
shayam
20
24000
shayam 20 24000
Self word is optional,you can use other word(sss)instead self.It is conventionally used in python
Ram 30 20000
This is MNT LAB YouTube channel Tutorials...
>>> 

Descriptions:-

  • Here we have defined a student class with 3 private data members as _name,_age,_salary.
  • We have defined four public methods set_data(),show_data(),get_data() and display().
  • We have used 'self' parameter(argument) in methods.Here 'self' is like 'this pointer' of c++ or this reference of java.we can used other variable name instead of self.We have explained it in above example.
  • self must be the first parameter of any function which belongs to the class.The first argument of the function in class must be the object itself.This is conventionally called self.
  • s1=student(): ,creates a nameless object of student class and stores its address in s1.
  • Methods of a class can be called using the syntax: object.method_name().
  • Whenever we call a method using a object,address of the object gets passed to the method implicitly.This address is passed in method in a variable called self.
  • s1.set_data('Ram',30,20000) calls the method set_data().First parameter (self) passed to this method is the address of the object.
  • When set_data() is called using s1 object,self contains the address of first object.But when set_data() method is called using s2 object,self contains the address of the second object of student class.
  • When show_data() method is called using s1 object then the values of student class will be printed. 
  • When we have called get_data() method.Here we have used sss parameter instead of self parameter.So we can use any variable name in place of self variable.

Constructors in Python:-

The class methods that begin with double underscore (__) are called special method.This special method is known as constructor.This special function is used for initialisation of objects or data members of the class .Constructors are called automatically when the instance(object) of the class is instantiated(created).

There are two ways to initialise an object.

     1.) Using methods like get_data(),set_data().
Advantage:-

Data is protected from manipulation from outside the class.

     2.) Using special member function(constructor) __init___().
Advantage:-

  • This __init__() special function (constructor) is called whenever a new object of that class is instantiated/created.
  • This __init__() is similar to constructor of c++/java. Constructor does not return any value so __init__() function also does not return ny value.
  • A class may have __init__() as well as set_data().
__init__() --> To initialise object.

set_data()--> To modify object

Types of constructors in python:-

There are mainly two types of constructors in python.

  1. Parameterised constructor
  2. Non-Parameterised constructor
We will learn it more details as given below:-

e.g.

class student:
    def set_data(self,a,b,c):
        self._name=a
        self._age=b
        self._salary=c
    def show_data(self):
        print(self._name)
        print(self._age)
        print(self._salary)      
    def display_contents(self):
       print(self._name,self._age,self._salary) 
       print("Self word is optional")
    def __init__(self,n='',a=0,s=0.0):
       self._name=n
       self._age=a
       self._salary=s 
#create the instance/object of the class
s1=student()
s1.set_data('Ram',30,20000)
s1.show_data()
#create the instance/object  of the class
s2=student()
s2.set_data('shayam',20,24000)
s2.show_data()
#create the instance/object  of the class
s3=student('Neha',25,23000)
s3.show_data()
s1.display_contents()
#create the instance/object  of the class
s4=student('sachin',26,53000)
student.show_data(s4)
Output:-
Ram
30
20000
shayam
20
24000
Neha
25
23000
Ram 30 20000
Self word is optional
sachin
26
53000
>>> 

Note:- If we do not define __init__() function,then python provides a default __init__() method.

Delete the attribute and objects :-

In python, we can delete the attributes and objects of any class using the del keyword.We have explained it with an example as given below:-

  • __del__() method (destructor) gets called automatically when an object goes out of scope.
  • __del__() method is similar to destructor function of c++.
e.g.
class student:
    id=10
    name='shyam'
    age=20
    def display(self):
        print(self.id)
        print(self.name)
        print(self.age)
    def __del__(self):
      print("delete object"+str(self))
#creating the instance of the class
s1=student()
s1.display()
print("")
print("After deleting the object of the class..")
del s1
s1.display()
#del student.age
print("After deleting the age attribute...")
s1.display()

Output:-
10
shyam
20

After deleting the object of the class..
delete object<__main__.student object at 0x000001E4B60C9AC8>
Traceback (most recent call last):
  File "C:\Users\RAMASHANKER VERMA\Desktop\class and object with del statement.py", line 17, in <module>
    s1.display()
NameError: name 's1' is not defined
>>> 

Accessing the object and class attributes:-

We can easily access the object and class attribute as given below:-
e.g.
class person:
    count=0
    def __init__(self,name='',size=0,color=''):
        self._name=name
        self.size=size
        self.color=color
        person.count+=1
    def display(self):
        print(self._name)
        print(self.size)
        print(self.color)
        print("Number of person count=",person.count)
p1=person('Rajesh',6,'Red')
p2=person('sachin',8,'yellow')
p1.display()
print("")
p2.display()
print("")
print(vars(p1))
print("")
print(dir(p2))

Output:-

Rajesh
6
Red
Number of person count= 2

sachin
8
yellow
Number of person count= 2

{'_name': 'Rajesh', 'size': 6, 'color': 'Red'}

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_name', 'color', 'count', 'display', 'size']
>>> 

Watch complete Python Lecture 36:-

For More...

  1. Create secure registration and login page in asp.net
  2. oops concepts in c#.net
  3. Function concepts in python with example
  4. Tuple concepts in python
  5. How to use break,continue and pass statement in python
  6. String in python part 5

0 comments:

Post a Comment

Powered by Blogger.