Object Oriented Programming in Python

Class is a blueprint or framework or template which can be used repeatedly. This is part of the concept known as DRY ( Don't Repeat Yourself ) in Python.
  • Video Tutorial on OOPs. Part - 1


Example of Class, Object and Method.

One college decided to give each student one Standard Envelope called student Kit. Inside each Kit we have mark sheet, attendance report and final certificate.

Our student Kit ( or standard Envelope ) is an example of our Class.

One standard format is used to give each student one mark sheet. This mark sheet is prepared using a blank format with college name , principal name, subject name and blank place is kept to write each student marks. This is an example of a standard template. For each student this format is used to give them their mark sheet.

The blank format is an example of a method,
Each student can be taken as an object

Each student can have mark sheet, attendance report, final certificates etc. These formatted documents are methods ( can be used by students or objects ).

There are functions ( methods ) within the class which can be used by the objects. So each student ( our object ) can use standard format (methods ) to generate mark sheets , attendance report or final certificate.

The functions in a class which belong to the object are known as methods


Declaring a Class

class student_kit():
    pass

Declaring an object

class student_kit():
    principal_name='Mr ABC' #class attributes

Alex=student_kit() # object declaration
In above code we have declared one class attribute as principal_name. All objects have access to this class attribute. So we can print the value of the class attribute by using object.
print(Alex.principal_name)
output is here
Mr ABC
While displaying mark sheet of 100 students we don't expect the name of the Principal to change frequently, ( student name changes all the time ) so we used a variable principal_name inside a class. When we use variable inside a class we call it class variable. This class variable is available to all the methods within the class.

Class variables are same as class attributes

methods

Methods of class are similar to functions. These methods are available to objects of the class. Methods can get access to class attributes.
class student_kit():
  class student_kit():
    principal_name='Mr ABC' #class attributes

  def attendance(self):  # method declaration         
    print("Is a student")

Alex=student_kit()   # object declaration
student_kit.attendance(Alex)  # Is a student (output)
Alex.attendance()          # Is a student(output)
Read more on instance attributes below.
Exercise methods ( basic )

Initialization of an object.

While creating an object we can assign attributes to it. We call it instance attribute. We will be using built in function __init__() for this. Every time the object is created this initialization process of executing __init__() is executed.
class student_kit():
    college_name='ABC College'  #class attributes

     #instance attributes
    def __init__(self,name,section):
        self.name= name
        self.section=section
        self.height=5  #instance attribute


Alex=student_kit('Alex','A')  # object declaration
print(Alex.name,Alex.section,Alex.height) #object accessing instance attributes
Output is here
Alex A 5
In above code the first parameter of the function __init__() is the object itself. We have given self as name of it, you can use any other name but for better understanding it is advisable to use the name self.
Exercise on Constructor

Instance attribute and class attributes

The variable principal_name is an class attribute which can be used by the objects. Class can also access the class attributes.
print(Alex.__class__.principal_name)  # Mr ABC
print(student_kit.principal_name)     # Mr ABC
print(Alex.principal_name)            # Mr ABC
However we can't access instance attribute as class property
print(student_kit.height)  # error
AttributeError: type object 'student_kit' has no attribute 'height' ( what is an AttributeError )

Example 2

We are preparing a Class for all carnivores animals.
Class Name is Animal
tiger is an object of Class Animal
each object has some properties ( or attributes ) as name , height and weight.

We have declared species ( as class attribute ) and its value is carnivores
Here is the code for this , ( Read all the comments against each statement ) . The last line will generate AttributeError ( What is AttributeError )
class Animal():

     #class attributes
    species='carnivores'

     #instance attributes
    def __init__(self1,name1,age,weight):
        self1.name= name1
        self1.age=age
        self1.weight=weight
        self1.height=5  #instance attribute

 #instantiate the Animal  class
tiger=Animal("Ronald",5,15)  # tiger is an object of Animal class

 # access the instance attributes
print("{} is {} years old animal".format( tiger.name, tiger.age))
print("{} weight is ={}".format( tiger.name,tiger.weight))
print("{} height is ={}".format( tiger.name,tiger.height))

 # object can access the class attributes directly
print("Species is {}".format(tiger.species))

 #object can access the class attributes
print("tiger is a {}".format(tiger.__class__.species)) #carnivores

 #class can access class attributes  
print(Animal.species)

 #instant attributes belong to object ( not to class ) 
print(Animal.height)  #AttributeError: type object 'Animal' has no attribute 'height'

Methods

Instance methods are functions defined inside the Class.
These methods are available for the objects to use. Here is an example.
class my_class():
  my_subject='Python'  # class attributes 
  #instance attributes
  def __init__(self,name,mark):
       self.name= name
       self.mark= mark
  def discount(self):
     if(self.mark > 50):
       return "Discount is avilable"
     else:
       return "No Discount"
Alex=my_class('Alex',40)  # object is defined 
print(Alex.discount())    # Discount method is used 
print(Alex.my_subject)    # Class attribute is used
Output
No Discount
Python

keyword del to remove the object

Once the object is deleted by del then same method will generate NameError as the object is no longer available.
class student_kit():
  
  def register(self,name):# method declaration 
    self.name=name        
    print("Welcome:",self.name)

s1=student_kit() # object declaration
s1.register('Alex')
del s1
s1.register('Ron') # NameError
The last line in above code will generate error. We can use try except error handling to manage the error.

delattr() to delete attribute of an object in Python
vars() to get __dict__ attribute of the object

Think : How attributes of a method is available for another method ?


Exercise_1 constructor ( basic ) Exercise_2 methods ( basic ) Exercise_3 methods ( basic ) Exercise with Solution ( Advance )

Inheritance

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    02-04-2020

    Nice

    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer