Python Class, Object, and Method: Definition and Example

This tutorial explains the definition of class, object, and method in Python. Further, it includes Python code examples for class, object, and method.

A class is a user-defined prototype, from which objects can be created. Classes can bundle data and functions together.

An object is an instance of a class. When an object is created, the class is said to be instantiated. 

Python Class Example

The following is an example of defining a class in Python and its output.

# define a class in Python
class A_simple_class:
  variable_0= 5

# print out a Python class
print(A_simple_class)

The following is print out for a Python class.

<class '__main__.A_simple_class'>

Python Object Example

The following is the syntax for defining an object.

Object_Name = Class_Name()

# define an object in Python
Object_0 = A_simple_class()

print(Object_0.variable_0)
5

Define a class with functions

We can add two functions within a class when defining the class. The following is the code example and output.

class Tesla:
    def fun1(model):
        print('This is a', model)

    def fun2(year):
        print(f"This model is {year}")


car_1=Tesla
car_1.fun1("Model 3")
car_1.fun2(2021)
This is a Model 3
This model is 2021

Use the __init__ in defining a class

You can also add __init__() in the definition of a class. The following is the code example and output.

You can compare it with the example shown above. While they generate the same output, the codes are slightly different.

class Tesla:
    def __init__(self,model, year):
        # the following defines instance variables 
        self.model=model
        self.year=year
    

    # instance method / object method
    def fun1(self):
        print('This is a', self.model)
   
    # instance method / object method
    def fun2(self):
        print(f"This model is {self.year}")

# create an object from the class
t_0=Tesla("Model 3",2021)

# call methods
t_0.fun1()
t_0.fun2()
This is a Model 3
This model is 2021

Modify instance variables and class variables

The following code example shows how to modify instance variables and object variables.

class Tesla:
    # class variable 
    Factory_name='Fremont'
    
    # constructor
    def __init__(self,model, year):
        # the following defines instance variables
        self.model=model
        self.year=year

    # instance method / object method
    def fun1(self):
        print('This is a', self.model)

    # instance method / object method
    def fun2(self):
        print(f"This model is {self.year}")

# create an object from the class
t_0=Tesla("Model 3",2021)


print("Before Modification:")
print(t_0.model)
print(t_0.Factory_name)

print("\n")


# modify object variables
t_0.model='Model Y'
t_0.Factory_name='Texas'

print("After Modification:")
print(t_0.model)
print(t_0.Factory_name)
Before Modification:
Model 3
Fremont


After Modification:
Model Y
Texas