Python – Object and Classe

The essential functionality of Python objects and classes will be covered in this course. You’ll discover what a class is, how to make one, and how to use one in your application.

Python Class

A class is a blueprint or prototype that is defined by the user and used to build things. Classes allow you to group data and functionality together. A new class introduces a new type of object, allowing for the creation of new instances of that type. Each instance of a class can have attributes linked to it to keep track of its status. Class instances can additionally have methods for changing their state (specified by their class).

Consider the following case: you want to keep track of the number of dogs with various characteristics such as breed and age. The first element of a list may be the dog’s breed, while the second element could be its age. What if there are 100 different dogs? How would you know which one is supposed to be which? What if you wanted to give these dogs other abilities? This lacks organization, which is precisely why classes are required.

A class creates a user-defined data structure with its own data members and member methods that can be accessed and utilized by establishing a class instance. A class is similar to an object’s blueprint.

Some points on Python class:  

  • Classes are created by keyword class.
  • Attributes are the variables that belong to a class.
  • Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute

Defining a Class in Python

Like function definitions begin with the def keyword in Python, class definitions begin with a class keyword.

The first string inside the class is called docstring and has a brief description of the class. Although not mandatory, this is highly recommended.

Here is a simple class definition.

class MyNewClass:
    '''This is a docstring. I have created a new class'''

A class creates a new local namespace where all its attributes are defined. Attributes may be data or functions.

It also has unique properties that start with double underscores . For example, doc returns the class’s docstring.

When we define a class, a new class object with the same name is produced. We may use this class object to access the various characteristics as well as create new objects of that class.

class Person:
    "This is a person class"
    age = 10

    def greet(self):

# Output: 10

# Output: <function Person.greet>

# Output: "This is a person class"


<function Person.greet at 0x7fc78c6e8160>
This is a person class

Python Objects

A Class’s instance is an Object. A class is similar to a blueprint, whereas an instance is a clone of the class that contains actual data. It’s no longer a concept; it’s a living creature, such as a seven-year-old pug. You can have a lot of dogs to make a lot of different scenarios, but without the class to guide you, you’d be lost and have no idea what information is needed.An object consists of : 

  • State: It is represented by the attributes of an object. It also reflects the properties of an object.
  • Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
  • Identity: It gives a unique name to an object and enables one object to interact with other objects.

Creating an Object in Python

We saw that the class object could be used to access different attributes.

It can also be used to create new object instances of that class (instantiation). The process of creating an object is comparable to calling a function.

>>> harry = Person()

This will create a new object instance named harry. We can access the attributes of objects using the object name prefix.

Attributes may be data or method. Methods of an object are corresponding functions of that class.

This means to say, since Person.greet is a function object (attribute of class), Person.greet will be a method object.

class Person:
    "This is a person class"
    age = 10

    def greet(self):

# create a new object of Person class
harry = Person()

# Output: <function Person.greet>

# Output: <bound method Person.greet of <__main__.Person object>>

# Calling object's greet() method
# Output: Hello


<function Person.greet at 0x7fd288e4e160>
<bound method Person.greet of <__main__.Person object at 0x7fd288e9fa30>>

You may have noticed the self parameter in the class’s function declaration, but we just called the method harry. greet() is a function that accepts no arguments. It was still functional.

Because the object itself is supplied as the first argument whenever an object calls its method, this is the case. As a result, harry.greet() becomes Person.greet() (harry).

Calling a method with an argument list of n is equal to calling the corresponding function with an argument list generated by putting the method’s object before the first argument.

As a result, the object itself must be the first argument of the class function. This is commonly referred to as “self.” It can be titled in any way you choose, however we strongly advise you to stick to the norm.

Now you must be familiar with class object, instance object, function object, method object and their differences.

Constructors in Python

Class functions that begin with double underscore __ are called special functions as they have special meaning.

Of one particular interest is the __init__() function. This special function gets called whenever a new object of that class is instantiated.

This type of function is also called constructors in Object Oriented Programming (OOP). We normally use it to initialize all the variables.

class ComplexNumber:
    def __init__(self, r=0, i=0):
        self.real = r
        self.imag = i

    def get_data(self):

# Create a new ComplexNumber object
num1 = ComplexNumber(2, 3)

# Call get_data() method
# Output: 2+3j

# Create another ComplexNumber object
# and create a new attribute 'attr'
num2 = ComplexNumber(5)
num2.attr = 10

# Output: (5, 0, 10)
print((num2.real, num2.imag, num2.attr))

# but c1 object doesn't have attribute 'attr'
# AttributeError: 'ComplexNumber' object has no attribute 'attr'


(5, 0, 10)
Traceback (most recent call last):
  File "<string>", line 27, in <module>
AttributeError: 'ComplexNumber' object has no attribute 'attr'

We created a new class to represent complex numbers in the preceding example. It has two functions: init() for initializing variables (defaults to zero) and get data() for appropriately displaying the number.

It’s worth noting that characteristics of an object can be created on the fly in the previous stage. For object num2, we generated and read a new attribute called attr. However, for object num1, this does not create that attribute.

Deleting Attributes and Objects

Any attribute of an object can be deleted anytime, using the del statement. Try the following on the Python shell to see the output.

>>> num1 = ComplexNumber(2,3)
>>> del num1.imag
>>> num1.get_data()
Traceback (most recent call last):
AttributeError: 'ComplexNumber' object has no attribute 'imag'

>>> del ComplexNumber.get_data
>>> num1.get_data()
Traceback (most recent call last):
AttributeError: 'ComplexNumber' object has no attribute 'get_data'

We can even delete the object itself, using the del statement.

>>> c1 = ComplexNumber(1,3)
>>> del c1
>>> c1
Traceback (most recent call last):
NameError: name 'c1' is not defined

Actually, it is more complicated than that. When we do c1 = ComplexNumber(1,3), a new instance object is created in memory and the name c1 binds with it.

On the command del c1, this binding is removed and the name c1 is deleted from the corresponding namespace. The object however continues to exist in memory and if no other name is bound to it, it is later automatically destroyed.

This automatic destruction of unreferenced objects in Python is also called garbage collection.

Leave a Comment

Your email address will not be published.