Beginner’s Guide to Python Class and Object

Python is an Object-Oriented Programming Language. The most important feature of object-oriented programming is class. It follows a bottom-up approach. Python also has a Procedural-Oriented Programming concept.

Most of the programming languages have the concept of OOP. Objects of Python contain variables, functions or methods.

For example, if there is an animal, then the animal would have some attributes and behaviours. The attributes of an animal would be age, leg, eye, or other body parts. The behaviour of animals would be eating, walking, sleeping, etc.

Each animal would have a different object. For example, dogs are an example of an animal object which can have the same behaviours and properties as an animal class.

Python Class

Classes are the blueprint or layout of the object. Classes are used to bind data and their functionality together. Data is attribute and functionality is behaviour. If we talk about python, then data is represented by class variables which are also called attributes.

The functionality or behaviour of a class is represented by functions. Where attributes maintain the state of a class instance, methods are used to modify the states of the instances.

There are some functions or methods inside the class and some variables are given related to it. Those functions and variables are collected on the same class and to access those data the object of that class is made. Multiple objects can be created for a class. We can also create an empty class in Python. For this, the class is defined and a pass statement is declared inside it, which tells that it is an empty class.

Let’s learn about the syntax of the class.

Syntax

class class_name:
    attributes # class variables
    behaviours # methods

class: The class keyword is used to define a class.

class_name: This is the name of the class. We can give any name to a class.

colon (:): It is mandatory to put a colon (:) after the class header declaration. It is used to define a block.

Attributes: These are the class variables.

Behaviours: These are the methods of a class.

Example

class First_class:
    num = 5
    def print_hello(self):
        print("Hello World")

print(First_class.print_hello)      # print_hello function

# Output :
<function First_class.print_hello at 0x7fe50f5849e0>

In the above example,

  • We have defined a class named as First_class.
  • In this class, there is one function defined as print_hello that can print a string and a variable named as num = 5.
  • We have sent self in that function. Let’s understand this.

In Python, the self keyword is used to refer to attributes from inside class methods. As given in the above example.

To use the self keyword, the self keyword must be defined as a parameter while defining the method.

If we define parameters other than the self keyword, then we pass arguments to them while calling the method.

How to create object in Python?

An object is an instance of a class. An object is created as a variable only. As the function is called on that variable, in the same way that class is stored on the variable as a function.

Syntax

object_name = class_name()

Example

class First_class:
  num = 5
  def print_hello(self):
      print("Hello World")

first_object = First_class() # Created a object of class First_class
print(first_object)

# Output :
<__main__.First_class object at 0x7fe50f5e22d0>

How to access class variable and methods?

We can access class variables and methods using class names and object names. To access the functions, we need to pass the object inside the function as a parameter. Let’s understand this with an example.

class First_class:
  num = 5
  def print_hello(self):
      print("Hello World")

first_object = First_class()

print("num variable using class name:",First_class.num) 

print("num variable using object:",first_object.num)          

print("print_hello function using class name:",First_class.print_hello)
print("print_hello function using object:",first_object.print_hello)        

First_class.print_hello(first_object)                   
first_object.print_hello()  

# Output :
First_class.num : 5
first_object.num : 5
First_class.print_hello : <function First_class.print_hello at 0x7fe50f5304d0>
first_object.print_hello : <bound method First_class.print_hello of <__main__.First_class object at 0x7fe50f541390>>
Hello World
Hello World

In the above example,

  • We have defined a class. In this class, there are function and variable.
  • At first print, class variable is accessed from First_class with class name.
  • At second, the class variable is accessed from the object “first_object" created by the class.
  • At third, print_hello function is accessed from First_class with class name but it returns function object.
  • At forth, print_hello function is accessed from object "first_object" created by Class but it returns ‘method object’.
  • Here First_class is passed to this parameter on definition self on the function of this class, similarly first_object object of this class is passed on argument.
  • This parameter is passed on definition self but no argument has been passed here, it means that when the function is accessed by the created object, then the object itself is passed on the argument. It needs to be given separately.

Class variable and Instance variable

A class variable can be accessed through its class name or its object, but to access the instance variable, the object of the class is required so we need to create an object first.

Instance Variable is created inside the constructor.

Let’s understand it with an example.

class First_class:
    cls_var = 1 # Class variable
    
    def __init__(self, ins_var): # constructor
        self.ins_var = ins_var   # Instance variable

first_object = First_class("JDBot") # Object
second_object = First_class("Rahul") # Object


print(f"Class Variable by Class Name :{First_class.cls_var}")
print(f"Class Variable by Class Object :{first_object.cls_var}")
print(first_object.cls_var, first_object.ins_var) # value of instance variable is "JDBot".
print(second_object.cls_var, second_object.ins_var) # Value of instance variable is "Rahul".

# Output :
Class Variable by Class Name :1
Class Variable by Class Object :1
1 JDBot
1 Rahul

__init__ method: This is a constructor. Values for class attributes can also be passed at run time. The init method is used to apply such values.

How to change value of class variable and instance variable?

Sometimes there are requirements to change class and instance variables for that class name or class object can be used to change the value of a variable of a class, but a class object is used to change the value of an instance variable.

Let’s understand it with an example.

class First_class:
    cls_var = 5 # class variable
    
    def __init__(self, ins_var): # constructor
        self.ins_var = ins_var   # Instance variable

first_object = First_class("JDBot") # object


print("Before :")
print(first_object.cls_var, first_object.ins_var)


First_class.cls_var = 10 # Updating the class variable
first_object.ins_var = "JDBot Updated" # Updating the instance variable

print("After :")
print(first_object.cls_var, first_object.ins_var)

# Output :
Before :
5 JDBot
After :
10 JDBot Updated

Conclusion

In the above blog, we have learned about class and objects in which initially we gathered information about the class and object with syntax and examples.

After that, we have learned about “How to access class and instance variables” and “how to update class and instance variable”. We have also gone through self keyword and __init__ method.


Up ↑

%d bloggers like this: