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 class is a blueprint of an object. Or Python class is a combination of initializing variables, defining methods, static methods, etc.

This section explains how to create a class in Python object-oriented programming, create an object or instance attributes, Modify an Object, and delete an object or instance with examples.

Creating an Empty Class in Python

You must use the pass keyword to create a Python class that does nothing or creates an empty one.

class Employee:
    pass

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

class Employee:
    Variable = Value
 

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

Python class Object

The Python class objects support both 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 CLName.Variable_name or CLName.function_name.
  • For the instantiation, you have to create an instance or a copy of that class. To create a new instance use instance_name = CLName(), 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 an attribute reference.

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

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

The last two statements used the attribute reference to access the variable value and the function result. So, 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.

class Employee:
    company = 'Tutorial Gateway'
 
    def func_message(self):
        print('Welcome to Programming')
 
emp = Employee()
print(emp.company)
emp.func_message()
 
print("-------------")
print(Employee.company)
print(Employee.func_message)
Tutorial Gateway
Welcome to 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, it automatically calls the __init__() function. You don’t have to call it.

In this Python class example, we used a simple print statement inside an __init__() function. Next, we created an object of Employee. 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 class properties in Python. Here, we used the function’s name, age, and gender and assigned those values in the following line. It means that when you create an object of the employee, 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 is 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 Programming')
 
emp1 = Employee('Jack', 25, 'Male') 

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

init output

Tutorial Gateway
Welcome to Programming
Jack
25
Male

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

In this example, we use n, a, gen as __init__ arguments and name, age, and gender as self initialization of a class. Hopefully, this might clear up 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 Programming')

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

init output

Tutorial Gateway
Welcome to 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, not the actual one. It means you can create n number of objects from a single one, and each instance might have different property values or method values.

In this example, we created an Employee. Next, we created two objects, emp1, and emp2, from that employee. 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 this World')
 
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 this World
Mike
25
Male

Tutorial Gateway
Welcome to this World
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 it 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 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 Programming

Tutorial Gateway
Tracy
27
Female
Tracy is learning Programming

Modifying the Python Class Variable example

Let us see how to modify the Python class variable using the 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.

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 of 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 Programming')
 
emp1 = Employee()
emp2 = Employee()
emp3 = Employee()
 
emp2.company = 'Py'
emp3.company = 'Apple'
 
emp1.func_message()
 
print(emp1.company)
print(emp2.company)
print(emp3.company)
print(emp1.company)
Welcome to Programming
Tutorial Gateway
Py
Apple
Tutorial Gateway

Modify Python Class Object Properties

This example shows how to modify the Object Properties. First, we created an instance emp1 of the Employee 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 Programs')

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 Programs
John
John is learning Programs

Delete Object Properties

In this Python class example, we show how to delete an object property. Here, emp1 = Employee(‘John’, 25, ‘Male’) creates an instance emp1 for Employee. Next, we are printing the name, age, gender, and 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). Finally, within the last statement, we again printed the name property of the emp1 object 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 Programming')
 
emp1 = Employee('John', 25, 'Male')
print(emp1.name)
print(emp1.age)
print(emp1.gender)
emp1.func_message()
 
del emp1.name 
print(emp1.name)
John
25
Male
John is learning 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. Next, we deleted the name property of the emp1 object using the del keyword. Next, we are printing the name of the emp2 instance and the emp1 instance.

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

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 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)
John
25
Male
John is learning 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 Classes and Objects

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

Next, we used the Python 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 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 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

Different ways of Creating a class

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

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 Programming')
         
emp = Employee()

std = Student()

per = Person()

create using a c_name or c_name() output

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

Python class self parameter

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

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 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 Programming')
 
    def func_msg(suresh):
        print('Tutorial Gateway Welcome ' + suresh.name)
 
emp1 = Employee('John', 25)
emp1.func_message()
emp1.func_msg()
John is learning Programming
Tutorial Gateway Welcome John