in , ,

Python Objects and Classes

Python Objects and Classes

Python Objects and classes

in this tutorial exercise, you will find out about the core functionality of Python objects and classes. You’ll realize what a class is, how to create it and use it in your program.

Python Objects and Classes

Python is an object-oriented programming language. Unlike procedure-oriented programming, where the primary accentuation is on capacities, object arranged programming stresses on objects.

An object is basically an assortment of information (factors) and techniques (works) that follow up on that information. Likewise, a class is a diagram for that object.

We can think of the class as a sketch (model) of a house. It contains all the insights concerning the floors, entryways, windows, and so forth. In light of these portrayals, we construct the house. House is the item.

As many houses can be produced using a house’s outline, we can make many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.

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 makes a new local namespace where every one of its traits is characterized. Characteristics might be information or capacities.

There are also exceptional traits in it that start with twofold underscores __. For instance, __doc__ gives us the docstring of that class.

As soon as we define a class, a new class object is made with a similar name. This class object permits us to get to the various credits just as to launch 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 my second class'
<function Person.greet at 0x7fc78c6e8160>
This is a person class

Making an Object in Python

We saw that the class object could be utilized to get to various characteristics.

It can likewise be utilized to make new object examples (launch) of that class. The method to make an object is similar to a function call.

>>> 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 methods. 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 function definition inside the class but we called the method simply as harry.greet() without any arguments. It still worked.

This is because, whenever an object calls its method, the object itself is passed as the first argument. So, harry.greet() translates into Person.greet(harry).

In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.

For these reasons, the first argument of the function in class must be the object itself. This is conventionally called self. It can be named otherwise but we highly recommend following the convention.

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

Constructors in Python

Class works that start with twofold underscore __ are called unique capacities as they have uncommon importance.

Of one specific intrigue is the __init__() work. This uncommon capacity gets called at whatever point another object of that class is started up.

This sort of capacity is additionally 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'

In the above example, we defined a new class to represent complex numbers. It has two functions, __init__() to initialize the variables (defaults to zero) and get_data() to display the number properly.

An interesting thing to note in the above step is that the attributes of an object can be created on the fly. We created a new attribute attr for object num2 and read it as well. But this does not create that attribute for object num1.

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 convoluted than that. At the point when we do c1 = ComplexNumber(1,3), another occasion object is made in memory, and the name c1 bind with it.

On the order del c1, this coupling is expelled and the name c1 is erased from the relating namespace. The item anyway keeps on existing 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.


Please feel free to give your comment if you face any difficulty here.

For more Articles click on the below link.

salman khan

Written by worldofitech

Leave a Reply

Python Object-Oriented Programming

Python Object-Oriented Programming

Python Inheritance

Python Inheritance