Python Classes And Objects- Object Oriented Programming

What is a Python Class?

A class in python is the blueprint from which specific objects are created. It lets you structure your software in a particular way. Here comes a question how? Classes allow us to logically group our data and function in a way that it is easy to reuse and a way to build upon if need to be. Consider the below image.

ClassesAndObjects - Python class - EdurekaIn the first image (A), it represents a blueprint of a house that can be considered as Class. With the same blueprint, we can create several houses and these can be considered as Objects. Using a class, you can add consistency to your programs so that they can be used in cleaner and efficient ways. The attributes are data members (class variables and instance variables) and methods which are accessed via dot notation.

  • Class variable is a variable that is shared by all the different objects/instances of a class.
  • Instance variables are variables which are unique to each instance. It is defined inside a method and belongs only to the current instance of a class.
  • Methods are also called as functions which are defined in a class and describes the behaviour of an object.

Now, let us move ahead and see how it works in PyCharm. To get started, first have a look at the syntax of a python class.

Syntax:

1
2
3
4
5
class Class_name:
statement-1
.
.
statement-N

Here, the “class” statement creates a new class definition. The name of the class immediately follows the keyword “class” in python which is followed by a colon. To create a class in python, consider the below example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class employee:
 pass
 #no attributes and methods
 emp_1=employee()
 emp_2=employee()
 #instance variable can be created manually
 emp_1.first='aayushi'
 emp_1.last='Johari'
 emp_1.email='aayushi@edureka.co'
 emp_1.pay=10000
 
emp_2.first='test'
 emp_2.last='abc'
 emp_2.email='test@company.com'
 emp_2.pay=10000
 print(emp_1.email)
 print(emp_2.email)

Output 

aayushi@edureka.co
test@company.com

Now, what if we don’t want to manually set these variables. You will see a lot of code and also it is prone to error. So to make it automatic, we can use “init” method. For that, let’s understand what exactly are methods and attributes in a python class.

Methods and Attributes in a Python Class

Now creating a class is incomplete without some functionality. So functionalities can be defined by setting various attributes which acts as a container for data and functions related to those attributes. Functions in python are also called as Methods. Talking about the init method, it is a special function which gets called whenever a new object of that class is instantiated. You can think of it as initialize method or you can consider this as constructors if you’re coming from any another object-oriented programming background such as C++, Java etc. Now when we set a method inside a class, they receive instance automatically. Let’s go ahead with python class and accept the first name, last name and salary using this method.

1
2
3
4
5
6
7
8
9
10
11
class employee:
    def __init__(self, first, last, sal):
        self.fname=first
        self.lname=last
        self.sal=sal
        self.email=first + '.' + last + '@company.com'
 
emp_1=employee('aayushi','johari',350000)
emp_2=employee('test','test',100000)
print(emp_1.email)
print(emp_2.email)

Now within our “init” method, we have set these instance variables (self, first, last, sal). Self is the instance which means whenever we write self.fname=first, it is same as emp_1.first=’aayushi’. Then we have created instances of employee class where we can pass the values specified in the init method. This method takes the instances as arguments. Instead of doing it manually, it will be done automatically now.

Next, we want the ability to perform some kind of action. For that, we will add a method to this class. Suppose I want the functionality to display the full name of the employee. So let’s  us implement this practically.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class employee:
    def __init__(self, first, last, sal):
        self.fname=first
        self.lname=last
        self.sal=sal
        self.email=first + '.' + last + '@company.com'
 
    def fullname(self):
            return '{}{}'.format(self.fname,self.lname)
 
emp_1=employee('aayushi','johari',350000)
emp_2=employee('test','test',100000)
print(emp_1.email)
print(emp_2.email)
print(emp_1.fullname())
print(emp_2.fullname())

Output 

 aayushi.johari@company.com
 test.test@company.com
 aayushijohari
 testtest

As you can see above, I have created a method called “full name” within a class. So each method inside a python class automatically takes the instance as the first argument. Now within this method, I have written the logic to print full name and return this instead of emp_1 first name and last name. Next, I have used “self” so that it will work with all the instances. Therefore to print this every time, we use a method.

Moving ahead with Python classes, there are variables which are shared among all the instances of a class. These are called as class variables. Instance variables can be unique for each instance like names, email, sal etc. Complicated? Let’s understand this with an example. Refer the code below to find out the annual rise in the salary. 

class employee:
    perc_raise =1.05
    def __init__(self, first, last, sal):
        self.fname=first
        self.lname=last
        self.sal=sal
        self.email=first + '.' + last + '@company.com'
 
    def fullname(self):
            return '{}{}'.format(self.fname,self.lname)
    def apply_raise(self):
        self.sal=int(self.sal*1.05)
 
emp_1=employee('aayushi','johari',350000)
emp_2=employee('test','test',100000)
 
print(emp_1.sal)
emp_1.apply_raise()
print(emp_1.sal)

Output 

 350000
 367500

As you can see above, I have printed the salary first and then applied the 1.5% increase. In order to access these class variables, we either need to access them through the class or an instance of the class. Now, let’s understand the various attributes in a python class.

Attributes in a Python Class

Attributes in Python defines a property of an object, element or a file. There are two types of attributes:

  • Built-in Class Attributes: There are various built-in attributes present inside Python classes. For example _dict_, _doc_, _name _, etc. Let me take the same example where I want to view all the key-value pairs of employee1. For that, you can simply write the below statement which contains the class namespace:

    print(emp_1.__dict__)
    

    After executing it, you will get output such as: {‘fname’: ‘aayushi’, ‘lname’: ‘johari’, ‘sal’: 350000, ’email’: ‘aayushi.johari@company.com’}

  • Attributes defined by Users: Attributes are created inside the class definition. We can dynamically create new attributes for existing instances of a class. Attributes can be bound to class names as well.

Next, we have public, protected and private attributes. Let’s understand them in detail:

NamingTypeMeaning
NamePublicThese attributes can be freely used inside or outside of a class definition
_nameProtectedProtected attributes should not be used outside of the class definition, unless inside of a subclass definition
__namePrivateThis kind of attribute is inaccessible and invisible. It’s neither possible to read nor to write  those attributes, except inside of the class definition itself


Next, let’s understand the most important component in a python class i.e Objects.

What are objects in a Python Class?

Objects - python class - AnswerGuruJi

As we have discussed above, an object can be used to access different attributes. It is used to create an instance of the class. An instance is an object of a class created at run-time.

To give you a quick overview, an object basically is everything you see around. For eg: A dog is an object of the animal class, I am an object of the human class. Similarly, there can be different objects to the same phone class. This is quite similar to a function call which we have already discussed. Let’s understand this with an example:

1
2
3
4
5
6
7
8
class MyClass:
 
   def func(self):
      print('Hello')
 
# create a new MyClass
ob = MyClass()
ob.func()

Moving ahead with python class, let’s understand the various OOPs concepts.

OOPs Concepts

OOPs refers to the Object-Oriented Programming in Python. Well, Python is not completely object-oriented as it contains some procedural functions. Now, you must be wondering what is the difference between a procedural and object-oriented programming. To clear your doubt, in a procedural programming, the entire code is written into one long procedure even though it might contain functions and subroutines. It is not manageable as both data and logic get mixed together. But when we talk about object-oriented programming, the program is split into self-contained objects or several mini-programs. Each object is representing a different part of the application which has its own data and logic to communicate among themselves. For example, a website has different objects such as images, videos etc. 
Object-Oriented programming includes the concept of Python class, object, Inheritance, Polymorphism, Abstraction etc. Let’s understand these topics in detail.

Python Class: Inheritance

Inheritance allows us to inherit attributes and methods from the base/parent class. This is useful as we can create sub-classes and get all of the functionality from our parent class. Then we can overwrite and add new functionalities without affecting the parent class. Let’s understand the concept of parent class and child class with an example.

Inheritance - python class - edurekaAs we can see in the image, a child inherits the properties from the father. Similarly, in python, there are two classes:

1. Parent class ( Super or Base class)

2. Child class (Subclass or Derived class )

;