Python Classes and Objects



Python Classes and Objects

Python is an object-oriented programming language. Unlike procedure-oriented programming, where the central importance is on functions, object-oriented programming focuses on objects.

Almost everything in Python is an object. An object collects data (variables) and methods (functions) that act on those data.

A class is a user-defined blueprint from which objects are created. Classes provide a mechanism for bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances to be made. Each class instance can have attributes and methods attached to it. Attributes of a class are used to maintain its state. On the other hand, methods of a class are used to modify its state.

A class creates a user-defined data structure, which holds its data members and member functions, which can be accessed and used by creating an instance of that class.


Defining a Class in Python

In Python, class definitions begin with the class keyword.

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

In the following example, a simple class definition.

class MyClass:
    """This is a docstring, A new class MyClass is created"""
    pass

In the above code, the class creates a new local namespace where all its attributes are defined. Attributes may be data or functions.

A class also contains special attributes that begin with double underscores __. For example, __doc__ provides the docstring of that class.

When we define a class, a new class object is created with the same name. This class object allows to access different attributes as well as to instantiate new objects of that class.

class Cat:
    "This is a cat class"
    age = 2

    def meow(self):
        print("Meow")

# Output: 2
print(Cat.age)

# Output <function Cat.meow>
print(Cat.meow)

# Output: "This is a cat class"
print(Cat.__doc__)

Output

2
<function Cat.meow at 0x7f5aca206290>
This is a cat class

Creating an Object in Python

As we saw before, a class object could be used to access various attributes.

The class object is also used to create new object instances of that class. The procedure to create an object is similar to a function call.

leo = Cat()

The above code will create a new object instance named leo. We can reach the attributes of objects using the object name prefix.

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

class Cat:
    "This is a cat class"
    age = 2

    def meow(self):
        print("Meow")

# create a new object of Cat class
leo = Cat()

# Output: <function Cat.meow>
print(Cat.meow)

# Output:  <bound method Cat.meow of <__main__.Cat object>>
print(leo.meow)

# Calling object's meow() method
# Output: Meow
leo.meow()

Output

<function Cat.meow at 0x7f72540be560>
<bound method Cat.meow of <__main__.Cat object at 0x7f72540ba250>>
Meow

As we see above, we noticed the self parameter in function definition inside the class; however, when we called the method simply as leo.meow() without any arguments.

The reason is whenever an object calls its method, the object itself is passed as the first argument. So, leo.meo() turns into Cat.meow(leo).

In Python, calling a method with a list n arguments is similar to calling the corresponding function with an argument list created by inserting the method's object before the first argument.

This is why 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.


Constructors in Python

Class functions that start with double underscore __ are special functions as they have special meanings.

One special function is the __init__(). The __init__() function gets called whenever a class's new object is instantiated.

The __init__() function is also called constructor in OOP (Object Oriented Programming). It is normally used to initialize all the variables.

class Dog:

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

    def infoDog(self):
        print(f'name: {self.name} age: {self.age}')

# Create a new Dog object
max = Dog("max", 2)

# Call infoDog() method
max.infoDog()

# Create another Dog object
# and create a new attribute "test"
luna = Dog("luna", 3)
luna.test = "test"

# Output luna values
print((luna.name, luna.age, luna.test))

# max object doesn't have attribute "test"
print(max.test)

Output

name: max age: 2
('luna', 3, 'test')

Traceback (most recent call last)
..
---> 25 print(max.test)
AttributeError: 'Dog' object has no attribute 'test'

In the above example, we defined a Dog class. It has two functions, __init__() to initialize the name and age variables, infoDog to output dog informations.

As we can see above, we can create attributes of an object on the fly. We created a new attribute test for object luna and read it as well. However, this does not create that attribute for object max.


Deleting Attributes and Object

The del statement can be used to delete any attribute of an object.

Let us see the following Python shell.

>>> luna = Dog("luna", 3)
>>> del luna.name 
>>> luna.infoDog()
Traceback (most recent call last)
. . .
AttributeError: 'Dog' object has no attribute 'name'

>>> del Dog.infoDog
>>> luna.infoDog()
Traceback (most recent call last)
. . .
AttributeError: 'Dog' object has no attribute 'infoDog'

The del statement can also be used to delete the object itself.

>>> max = Dog("max", 2)
>>> del max
>>> max
Traceback (most recent call last)
. . .
NameError: name "max" is not defined

When we type max = Dog("max", 2), a new instance object of the Dog object is created in memory, and the name max binds with it.

After executing del max, this binging is removed, and the name max is deleted from the corresponding namespace. However, the object 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.



ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.