9 – Classes in Python

Python is an Object Oriented Programming Language. So working with classes and Objects are easier. Some reasons to go for classes are listed below.

  • Easier troubleshooting
  • Reuse of code using Inheritance
  • Modules and Exception are built using Classes

SYNTAX FOR CLASS:

__init__  is constructer for classes in python

1
2
3
4
5
6
7
8
9
10
11
class Classname:
   'Description'
   #Object Initialization
   x=0
 
   def __init__(self,a1):
      self.a1 = a1
      #a1 is argument
 
   def function(self):
     print "Function"

OBJECT:

Object is an instance to a class. Variables and Functions in classes are assesed using objects.

1
2
objectname=Classname(Arguments)
objectname.function()

EXAMPLE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class MYBTECHPROJECTS:
   'Learn what you like'
   #Object Initialization
   total_no_of_posts=26
 
   def __init__(self,name):
      self.name = name
 
 
   def return_no_of_posts(self,lang):
     if lang=="python":
         return 10
     if lang=="NodeMCU":
         return 6
 
 
o=MYBTECHPROJECTS("Gowtham")
print "Documentation     ", o.__doc__
print "Total no of posts ",o.total_no_of_posts
print "Author name       ",o.name
print "No of posts in Python  ",o.return_no_of_posts("python")
print "No of posts in ModeMCU ",o.return_no_of_posts("NodeMCU")

OUTPUT

1
2
3
4
5
6
7
>> 
Documentation      Learn what you like
Total no of posts  26
Author name        Gowtham
No of posts in Python   10
No of posts in ModeMCU  6
>>>

INHERITANCE:

Inheritance is a process of  inheriting a child class from its parent class. Child class can access variables and functions of parent class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#Base Class
class MYBTECHPROJECTS:
   'Learn what you like'
   #Object Initialization
   total_no_of_posts=26
 
   def __init__(self,name):
      self.name = name
 
 
   def return_no_of_posts(self,lang):
     if lang=="python":
         return 10
     if lang=="NodeMCU":
         return 6
 
#Child  class        
class Child(MYBTECHPROJECTS):
   def __init__(self):
      print "Child constructor"
 
 
o=Child()
print "Documentation     ", o.__doc__
print "Total no of posts ",o.total_no_of_posts
print "No of posts in Python  ",o.return_no_of_posts("python")
print "No of posts in ModeMCU ",o.return_no_of_posts("NodeMCU")

OUTPUT

1
2
3
4
5
6
7
>> 
Child constructor
Documentation      None
Total no of posts  26
No of posts in Python   10
No of posts in ModeMCU  6
>>>
THANK YOU

 

SHARE THIS!!!

Gowtham S

Gowtham is a programming enthusiast. His field of interest includes Arduino, NodeMCU, Raspberry Pi, and Python. To know more about him visit https://mybtechprojects.tech/about-us/.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.