Python Class

Python is an Object-Oriented Programming Language (OOPS). It means everything in python is an object or instance of some class. In simple words, the Python class is a blueprint of an object. Or, Python class is a combination of initializing variables, defining methods, static methods, class methods, etc. In this section, we explain to you how to create a class in Python, creating an object or instance of a class, Modify Object, delete an object, or instance with examples.

Creating an Empty Class in Python

If you want to create a Python class that does nothing or creates an empty class, you must use the pass keyword.

# Python Class example
 
class Employee:
    pass

The following example shows how to declare a variable and create a method inside a Python class. There are different kinds of methods, which we discuss in the later section. For now, understand the Python class syntax.

class Employee:
    Variable = Value
 

    def function_name(self):
        Statements 
    …………..

Python class Object

In Python, class objects supports both the attribute reference and instantiation. You can use either of them to call the class attributes. It is an example of both the instantiation and the attribute reference.

  • The attribute reference uses ClassName.Variable_name or ClassName.function_name. 
  • For the instantiation, you have to create an instance of that Python class (or a copy of that class). To create an instance use instance_name = class_Name(), to call the variable instance_name.variable_name and to call the method instance_name.method_name()

Here, emp = Employee() is creating an instantiation, and emp.company inside print means calling class variable. Next, Employee.company is an example of attribute reference.

class Employee:
    company = 'Tutorial Gateway'
 
emp = Employee()
print(emp.company)
 
print("-------------")
print(Employee.company)

class object output

Tutorial Gateway
-------------
Tutorial Gateway

In this Python class example, we declared a variable company, and we defined a function with a self parameter that prints a welcome message. Next, we created an object emp1 for Employee class. By using this object emp1, we are accessing the company variable, and func_message().

Within the last two statements, we used the attribute reference to access the variable value and the function result. By using attribute reference, you can print the variable value. However, Employee.func_message returns the function object but not the actual function result. So, you should remember this concept while working with attribute references in a python class.

class Employee:
    company = 'Tutorial Gateway'
 
    def func_message(self):
        print('Welcome to Python Programming')
 
emp = Employee()
print(emp.company)
emp.func_message()
 
print("-------------")
print(Employee.company)
print(Employee.func_message)

class with functions or methods output

Tutorial Gateway
Welcome to Python Programming
-------------
Tutorial Gateway
<function Employee.func_message at 0x7f831ddd8d30>

Python __init() function

By default, all the Python classes in real-time have an __init__() function. Use this function to assign values to the properties of an object. When you create an object of a Python class, it automatically calls the __init__() function. You don’t have to call it.

In this Python example, we used a simple print statement inside an __init__() function. Next, we created an object of Employee class. As you can see, it is directly printing the message.

class Employee:
    company = 'Tutorial Gateway'

    def __init__(self):
        print('Hello World')
 
    def func_message(self):
        print('Welcome to Python Programming')
 
emp1 = Employee() # Created an Instance
 
print(emp1.company)
emp1.func_message()
Python Class 4

Here, we use the __init__() function to add values to the properties in a Python class. Here, we used name, age, gender in the function, and assigned those values in the next line. It means, when you create an object of employee class, you have to provide the name, age, and gender (while creating the object itself).

For instance, if you create an object emp1 = Employee() without the argument values, then the following error raised. TypeError: __init__() missing 3 required positional arguments: ‘name’, ‘age’, and ‘gender’

class Employee:
    company = 'Tutorial Gateway'
 
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
 
    def func_message(self):
        print('Welcome to Python Programming')
 
emp1 = Employee('Jack', 25, 'Male') 

print(emp1.company)
emp1.func_message()
print(emp1.name)
print(emp1.age)
print(emp1.gender)

Python init output

Tutorial Gateway
Welcome to Python Programming
Jack
25
Male

From the above Python class example, it might confuse you to declare the argument because we used the same names: name, age, gender all the time. However, it is not mandatory to use like that, but it is a best practice to do so. 

In this Python class example, we are using n, a, gen as __init__ arguments and name, age, gender as self initialization. Hopefully, this might clear your confusion.

class Employee:
    company = 'Tutorial Gateway'

    def __init__(self, n, a, gen):
        self.name = n
        self.age = a
        self.gender = gen

    def func_message(self):
        print('Welcome to Python Programming')

emp1 = Employee('Johnson', 29, 'Male')
 
print(emp1.company)
emp1.func_message()
print(emp1.name)
print(emp1.age)
print(emp1.gender)

Python init output

Tutorial Gateway
Welcome to Python Programming
Johnson
29
Male

Multiple class Objects in Python

When you create an object or instance of a Python class, it holds a copy of that class, not the actual class. It means you can create n number of objects from a single class, and each instance might have different property values or method values.

In this Python class example, we created an Employee class. Next, we created two objects emp1 and emp2 from that employee class. As you can see, each instance has different names, ages, and gender. Next, we are printing those values as output, and you can see they work!.

class Employee:
    company = 'Tutorial Gateway'

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
 
    def func_message(self):
        print('Welcome to Python Programming')
 
emp1 = Employee('Mike', 25, 'Male')
print(emp1.company)
emp1.func_message()
print(emp1.name)
print(emp1.age)
print(emp1.gender)
 
print()
emp2 = Employee('Tracy', 27, 'Female')
print(emp2.company)
emp2.func_message()
print(emp2.name)
print(emp2.age)
print(emp2.gender)
Tutorial Gateway
Welcome to Python Programming
Mike
25
Male

Tutorial Gateway
Welcome to Python Programming
Tracy
27
Female

This Python class example is the same as above. However, this time we modified the func_message(self) function definition. It accepts the name (instance variable) and attaches to the message that we print as an output. Let me call this message from two instances emp1 and emp2.

class Employee:
    company = 'Tutorial Gateway'

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
 
    def func_message(self):
        print(self.name + ' is learning Python Programming')
 
emp1 = Employee('Mike', 25, 'Male')
print(emp1.company)
print(emp1.name) # Mike
print(emp1.age) #25
print(emp1.gender)
emp1.func_message()
 
print()
emp2 = Employee('Tracy', 27, 'Female')
print(emp2.company)
print(emp2.name) #Tracy
print(emp2.age) # 27
print(emp2.gender)
emp2.func_message()

As you can see emp1.func_message() replaced the self.name as Mike and emp2.func_message() replaced self.name with Tracy.

Tutorial Gateway
Mike
25
Male
Mike is learning Python Programming

Tutorial Gateway
Tracy
27
Female
Tracy is learning Python Programming

Modifying the Python Class Variable

Let us see how to modify the Python class variable using the class Objects. First, we declared a company variable and a function that prints a welcome message. Next, we created three instances emp1, emp2, and emp3 of the Employee class.

Next, we used Object_name.Variabel_name = New_Name to change the name of the company for emp2 and emp3 objects. It changes the company names for both these instances. Next, we are printing the company variable from all these three instances.

class Employee:
    company = 'Tutorial Gateway'
 
    def func_message(self):
        print('Welcome to Python Programming')
 
emp1 = Employee()
emp2 = Employee()
emp3 = Employee()
 
emp2.company = 'Python'
emp3.company = 'Apple'
 
emp1.func_message()
 
print(emp1.company)
print(emp2.company)
print(emp3.company)
print(emp1.company)
Welcome to Python Programming
Tutorial Gateway
Python
Apple
Tutorial Gateway

Modify Python Object Properties

This example shows how to modify the Python Object Properties. First, we created an instance emp1 of the Employee class with the required fields. Next, we are printing the available values as an output.

Here, emp1.name = ‘John’ (object_name.property_name = New_Value) statement updates the existing emp1 name (Mike) to John. Let me check the same by printing the emp1 name one more time.

class Employee:
    company = 'Tutorial Gateway'

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
 
    def func_message(self):
        print(self.name + ' is learning Python Programming')

emp1 = Employee('Mike', 25, 'Male')
print(emp1.name)
print(emp1.age)
print(emp1.gender)
emp1.func_message()
 
emp1.name = 'John'
print(emp1.name)
emp1.func_message()

See that the last two statements are printing the new name, John.

Mike
25
Male
Mike is learning Python Programming
John
John is learning Python Programming

Delete Python Object Properties

In this Python class object example, we show how to delete an object property. Here, emp1 = Employee(‘John’, 25, ‘Male’) creates an instance emp1 for Employee class. Next, we are printing the name, age, gender, and the message from the func_message() method. 

Next, we used the del keyword to delete the emp1 object property called name (del instance_name.property_name). Within the last statement, we again printed the name property of the emp1 object that we deleted. As you can see, it displays an error ‘Employee’ object has no attribute’ name’. It means we successfully deleted the object property. Similarly, you can delete age by del emp1.age and gender by del emp1.gender.

class Employee:
    company = 'Tutorial Gateway'
 
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
 
    def func_message(self):
        print(self.name + ' is learning Python Programming')
 
emp1 = Employee('John', 25, 'Male')
print(emp1.name)
print(emp1.age)
print(emp1.gender)
emp1.func_message()
 
del emp1.name 
print(emp1.name)

Deleting Python class object properties

John
25
Male
John is learning Python Programming
Traceback (most recent call last):
  File "/Users/suresh/Desktop/simple.py", line 19, in <module>
    print(emp1.name)
AttributeError: 'Employee' object has no attribute 'name'

Remember, deleting an instance property doesn’t affect the other instance property. This Python class example is the same as above. However, this time we created two Instances emp1 and emp2 for the Employee class. Next, we deleted the name property of the emp1 object using the del keyword. Next, we are printing the name of emp2 instance and emp1 instance.

emp2.name returns the name as Nancy but, emp1.name is throwing an error because we deleted it.

class Employee:
    company = 'Tutorial Gateway'
 
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
 
    def func_message(self):
        print(self.name + ' is learning Python Programming')
 
emp1 = Employee('John', 25, 'Male')
emp2 = Employee('Nancy', 27, 'Female')
print(emp1.name)
print(emp1.age)
print(emp1.gender)
emp1.func_message()
 
del emp1.name
print(emp2.name)
print(emp1.name)

Deleting a Python instance property output

John
25
Male
John is learning Python Programming
Nancy
Traceback (most recent call last):
  File "/Users/suresh/Desktop/simple.py", line 21, in <module>
    print(emp1.name)
AttributeError: 'Employee' object has no attribute 'name'

Delete Python Class Object

In this Python class example, we use the same class that we defined in our previous example. Here, first, we create an object of Employee class and displaying the employee name, age, gender, and the message from the func_message() method. Please refer static methods article.

Next, we used the del keyword to delete the class object emp1 (del Object_name). It deletes the instance emp1 that we created earlier. In the last statement, we called the func_message() method with an emp1 object to check whether the object still exists or not. As you see, it was throwing an error name ’emp1′ is not defined. It means, we deleted the emp1 object by the del statement.

class Employee:
    company = 'Tutorial Gateway'
 
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
 
    def func_message(self):
        print(self.name + ' is learning Python Programming')
 
emp1 = Employee('John', 25, 'Male')
print(emp1.name)
print(emp1.age)
print(emp1.gender)
emp1.func_message()
 
del emp1
emp1.func_message()
John
25
Male
John is learning Python Programming
Traceback (most recent call last):
  File "/Users/suresh/Desktop/simple.py", line 19, in <module>
    emp1.func_message()
NameError: name 'emp1' is not defined

Options for Creating Python class

Here, we show the different ways to create a class in python. As you can see, either you can use class_name or class_name() or class_name(object). The last option with the object is the latest one to create a class in python. If you look close to object creation, we used the same approach to create the object for all those three classes.

class Employee:
    def __init__(self):
        print('Msg from Employee : Welcome to Tutorial Gateway')
 
class Student():
    def __init__(self):
        print('Msg from Student: Hello World!')
 
class Person(object):
    def __init__(self):
        print('Msg from Person: Welcome to Python Programming')
         
emp = Employee()

std = Student()

per = Person()

creating class using a class_name or class_name() output

Msg from Employee : Welcome to Tutorial Gateway
Msg from Student: Hello World!
Msg from Person: Welcome to Python Programming

Python class self parameter

The Python self parameter is nothing but a reference to the current instance of a class. We have to use this Python class self parameter as the first parameter, which helps us to access the variables belongs to the class.

If you don’t like the keyword self, then use any word as a self parameter. However, it has to be the first parameter. In this Python class example, we used suresh instead of self in the third method.

class Employee:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def func_message(self):
        print(self.name + ' is learning Python Programming')
 
    def func_msg(suresh):
        print('Tutorial Gateway Welcome ' + suresh.name)
 
emp1 = Employee('John', 25)
emp1.func_message()
emp1.func_msg()

class self parameter output

John is learning Python Programming
Tutorial Gateway Welcome John