Register Login

Classes and Instances in Python

All programmers know Python has been an object-oriented programming language since it existed. In an object-oriented programming language, a class plays the leading role. It means classes are building blocks of an object-oriented programming language.

This article will help a Python programmer become an expert and handle Python's object-oriented programming pieces, like classes and instances.

What are classes in Python?

Class is the most basic entity of Python because it acts as the core of object-oriented programming. Because of this, users can create and use classes and instances that are downright simple and easy.

Everything that a user sees in Python is an object, such as integers, functions, dictionaries, lists, and many other entities. It is a subpart of a class. Every Python object has a type, and users can create the object types using classes.

Syntax:

class Class_name:
	#body of the class

Let us take an example to understand the Python classes:

class Employees:
	pass

The class name is "Employees," and it does not inherit from another Python class. Usually, users capitalize the Class names, but they can only do this for a conventional technique, which is not always necessary.

Then, they have to create an indentation of everything within a class, similar to how they create indentation within a function, for loop, if statement, or any other block of code.

Note:

The starting line of the code block not indented is outside the scope of the class

Explanation:

In the above example, we have created a Python class with the name of the class "Employees." Inside the class, the "pass" is the no-operation statement.

This Student class does not specify any attributes or methods, but syntactically, users need to define something in the class definition, and thus the pass statement.

Important:

The scope of a class is the region from where the objects (functions, variables, and attributes) of a class are accessible. By default, all the objects of a class are public.

Users can access any member from outside the class environment.

Let us see another example of a Python class:

class Employee:
    "This is an Employee class"
    salary = 40000
    def demo (self):
        print ('Salary')
print (Employee.salary)
print (Employee.demo)
print (Employee.__doc__)

Output:

What are instances in Python, and how to define and call an instance method?

Instances are objects of a class in Python. In other words, users can define an instance of a particular class as an individual object.

Users can define the Instance methods inside a Python class, similar to how they define a regular function.

  • First, users use the "def" keyword to define an instance method.
  • Secondly, while defining the instance methods, users use the "self" as the first parameter within the instance method. The self parameter directs to the existing object.
  • Lastly, users can use the self parameter to access or change the existing attributes of the Python object.

Calling an instance method:

Users can use the dot operator (.) to call the instance method and execute the block of code or action specified within the instance method.

Let us see an example to understand it more clearly:

class Employees:
# using the constructor
    def __init__(self, employee_name, employee_salary):
    # Using Instance variable
        self.name = employee_name
        self.salary = employee_salary

    # accessing the instance variable from instance method
    def show(self):
        print('Employee Name:', self.name, 'Employee Salary:', self.salary)

# Here, we are creating the first object
print('First Employees')
a = Employees("A", 34500)
# calling the instance method
a.show()

# Here, we are creating the second object
print('Second Employees')
b = Employees("B", 35000)
# call instance method
b.show()

Output:

Explanation:

The self.name and the self.age are instance variables of the Employees class. To access the instance variable from the instance method, users need to use the show() function.

Then, we created two objects with two different details of employees, and then we called the instance method according to the employee name.

Class and Instance Attributes in Python:

In Python, users can use attributes of a Class that belongs to the class itself. All the instances of that class can share this.

Code Snippet:

# Here, we are writing the Python code in Online GDB
class demo:
 a = 0  # class attribute
 def increase(self):
  demo.a +=5

# Here, we call the increase() on the object
x1 = demo()
x1.increase()  
print(x1.a)

# Here, we call the increase() on one more object  
x2 = demo()
x2.increase()
print(x2.a)
print(demo.a)

Output:

Unlike class attributes, Python objects do not share instance attributes. All the Python object has a copy of their instance attribute.

Code Snippet:

# Here, we are writing a Python program to explain the instance attributes.
class demo:
 def __init__(self):
  self.name = 'A'
  self.sal = 30000
 def show(self):
  print(self.name)
  print(self.sal)
a = demo()
print("The dictionary is :", vars(a))
print(dir(a))

Output:

Class and Instance variables in Python:

When users define a class, the variables they use within a class are the class variables, and the variables used within a class instance are the instance variables. Users do not use class variables as frequently as they use instance variables.

The Python instances of the class have instance variables. It indicates that every object or instance has its unique instance variables, i.e.,  the instance variables are different for each object or instance of a class.

Code:

class demo:
	class_variable = "Hello, this is Python"
a = demo()
print(a.class_variable)

Output:

Code Snippet of using instance variables:

class demo:
    # constructor
    def __init__(self, name, salary):
        # Instance variable
        self.name = name
        self.sal = salary

# Here, we are creating the first object
a = demo("Jekkie", 35000)

# accessing the instance variable
print('First Object')
print('Name:', a.name)
print('Age:', a.sal)

# Here, we are creating the second object
b= demo("Marry", 34000)

# accessing the instance variable
print('Second Object 2')
print('Name:', b.name)
print('Age:', b.sal)

Output:

Conclusion:

This article is all about classes and instances in Python. These are the basic components of a Python program. Thus, users can carefully handle the class and instance attributes and variables as they affect the entire class.

If users use these carelessly, undesired outputs showing errors may occur.


×