Welcome

sampleqa.in tutorials, Python Programming  tutorial,Python Classes

Python Classes


Class: A class is a blueprint, an idea of something, It doesnt exists as a usable function, rather it describes how to make something. This blueprint can be used to create object(s).

    There are two types of classes,

  • Builtin Classes
  • User-Defined Classes

Built-in Classes are declared and defined in Python Framework

for example: built-in class str ,it has all methods related to string handling, all string related methods are packed together,to form a single unit called string class.

Similiary int,float,list,tuple,set and dictionary all are built-in classes.

Finding the Type of the Class
>>> type(1)

<class 'int'>
>>> type(1.1)
<class 'float'>
>>> type([1])
<class 'list'>
>>> type((1))
<class 'int'>
>>> type((1,))
<class 'tuple'>
>>> type({1,})
<class 'set'>
>>> type({1:1,})
<class 'dict'>

User-Defined Classes are declared and defined by the Programmer

User defined class Syntax:
class  class_name(object):
	statements
	....
	statements

	method1
	medthod2
	........
	methodN

Every class starts with class keyword followed by class name. class can contain class variables ,methods. Every class is derived from object(specified in the parenthesis) class,Which is a base class for all objects in Python, Which provides basic functionality to every object

Declare a Class Example:

   	class ABC:
   	   pass
   
   

class ABC declared it has no statements.or it has only null statement

    	class ABC:
    	   def display():
    	     print("Hello Object Oriented Programming.....")
    

above class ABC is declared with one method called display,which prints a message. Functions inside a class is called as methods

Creating an Object of ABC class

    		a=ABC() # a is an object of ABC
    		
    		a.display() # calling display method using ABC instance 'a'
    		
    		#Prints
    		
    		Hello Object Oriented Programming.....
    		
    

Classes with Constructors

     A Class can have one or more Constructores to intitialize instance variables. Constructors are automatlically called whenver object of the class is created, Constructors use dunder method called __init__ to initialize variables. Constructors are special methods in Python like in C++ and Java classes.

Constructors Examples

class One:
 def __init__(self):
   self.count = 0;
 def incr(self):
 	self.count+=1;
 def decr(self):
    self.count -=1
 def reset(self):
    self.count = 0;
 def print(self):
   print("count is ",self.count)
   
o=One()

o.print()

o.incr()
o.incr()

o.print()

o.decr()
o.print()

o.reset()
o.print()         

---------------- Output ..............

count is  0
count is  2
count is  1
count is  0


      

The above class has one constructor __init__ and various methods for incrementing and decrementing and reset and priniting.

    Constructor Initialize internal instance variable count to 0.
  • __init__
  •    Initializes instance variable count to 0
  • incr
  •    increments instance var count by 1
  • decr
  •    decrements instance var count by 1
  • reset
  •    count set to 0
  • print
  •    prints count value

Note: Each method takes self parameter , which is a reference to the object itself. like this keyword in C++/Java

Constructors Examples2

Following class has constructor takes parameter.

Circle class takes one parameter called radius, using which area and perimeter of the circle calculated.

  • __init__ method
  • constructor takes one param called radius
  • area method
  • area of the circle calculated
  • perimeter method
  • perimter of the circle calculated

import math

class Circle:
  def __init__(self,radius):
    self.radius = radius
  def area(self):
    return math.pi * self.radius ** 2
  def perimeter(self):
   return 2 * math.pi * self.radius;   		
    
radius=10       
#Circle object is created passing radius as input
r = Circle(radius) 

#area of the circle is calculated
print("Radius {} area {}".format(radius,r.area()))           

#Perimeter of the circle is calculated
print("Radius {} paremeter {}".format(radius,r.perimeter()))  


                
-----------------Output---------------
Radius 10 area 314.1592653589793
Radius 10 paremeter 62.83185307179586
      
       

Conclusion

     In this tutorial, we discused about Python Classes, There are 2 types of classes

  • built-in Classes
  •      Python Data Types are implemented as a Classes

  • User-Defined Classes
  •      How to create a Class, Difference between Function and Method,How to create a Class,Creating an Object of a Class,Calling Methods of an Object, Constructors and, Instance Variables etc.,

>>>   Class Variables and static methods