Learn Class and Object in Python

Python is an object-oriented programming language. Unlike procedural programming, which emphasizes functions, object-oriented programming focuses on objects. This article Quantrimang will explore Class and Object in depth, inviting readers to follow.

Python is an object-oriented programming language. Unlike procedural programming, which emphasizes functions, object-oriented programming focuses on objects.

Object (Object) is simply a collection of data (variables) and methods (functions) that operate on those data. And, class (class) is a blueprint for the object.

We can think of class as a sketch of a house. It contains all the details about floors, doors, windows, . Based on these descriptions, we will build houses. So this house is the object.

Learn Class and Object in Python Picture 1

Since many houses can be made from a description, we can create many objects from one class. An object is also called an instance of a class and the creation of this object is called instantiation.

See also: Learn about Class, Object and Instance in object-oriented programming

Declare Class

Just like declaring functions starting with a def keyword, declaring the class in Python uses the class keyword.

The first character line is called docstring - a brief description of the class. This Docstring is not required but recommended.

 class MyNewClass: 
'''Đây là docstring. Một lớp mới vừa được khai báo.'''
pass

This is a simple class declaration.

The class creates a new local namespace that becomes the place where its properties are declared. Attributes can be functions or data.

There are also special attributes that start with double underscores (__). For example: __doc__ will return a descriptive docstring string of that class.

As soon as a class is declared, a new class object will be created with the same name. This class object allows us to access various properties as well as to create new objects of that class.

 class MyClass: 
"Đây là class thứ 2 được khởi tạo"
a = 10
def func(self):
print('Xin chào')

# Output: 10
print(MyClass.a)

# Output:
print(MyClass.func)

# Output: 'Đây là class thứ 2 được khởi tạo'
print(MyClass.__doc__)

After running the program, the result returned is:

 10 

Đây là class thứ 2 được khởi tạo

Create objects in Python

As mentioned in previous lessons, objects in the class can be used to access different properties and create new instances of that class. The procedure to create an object is similar to the way we call the function.

 ob = MyClass() 

This command has created a new object named ob.

A better example of object creation includes attributes, methods:

 class MyClass: 
"Đây là class thứ 3 được khởi tạo"
a = 10
def func(self):
print('Xin chào')

ob = MyClass()

# Output:
print(MyClass.func)

# Output: >
print(ob.func)

# Gọi hàm func()
# Output: Xin chào
ob.func()

You can see that when defining the function in the class, we have the parameter self, but when calling the obj.func () function without parameters, there is no error. Because, whenever the object calls methods, the object will pass the first parameter automatically. That means obj.func () is equivalent to MyClass.func (obj)

Constructor in Python

The function in Class begins with a double underscore (__) as special functions, which have special meanings.

One of them is __init __ () function. This function is called whenever an object is initialized, a new variable in the class and called a constructor in object-oriented programming.

 class SoPhuc: 

def __init__(self,r = 0,i = 0):
self.phanthuc = r
self.phanao = i

def getData(self):
print("{}+{}j".format(self.phanthuc,self.phanao))

# Tạo đối tượng số phức mới
c1 = SoPhuc(2,3)

# Gọi hàm getData()
# Output: 2+3j
c1.getData()

# Tạo đối tượng số phức mới
# tạo thêm một thuộc tính mới (new)
c2 = SoPhuc(5)
c2.new = 10

# Output: (5, 0, 10)
print((c2.phanthuc, c2.phanao, c2.new))
 
# Đối tượng c1 không có thuộc tính 'new'
# AttributeError: 'SoPhuc' object has no attribute 'new'
c1.new

In the above example, we declare a new class to represent complex numbers. It has two functions, __init __ () to initialize variables (default is 0) and getData () to display the correct number.

Note that the added properties of the object can be created quickly, as in the above example, we have created a new 'new' attribute for the c2 object and can immediately call out. However, this new attribute will not apply to previously declared objects like c1.

Delete properties and objects

Object properties can be deleted with the del command .

 >>> c1 = SoPhuc(2,3) 
>>> del c1.phanao
>>> c1.getData()
Traceback (most recent call last):
.
AttributeError: 'SoPhuc' object has no attribute 'phanao'

>>> del SoPhuc.getData
>>> c1.getData()
Traceback (most recent call last):
.
AttributeError: 'SoPhuc' object has no attribute 'getData'

You can even delete the object itself using the del command .

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

After being deleted, the object still exists on memory, but then the destruction method of Python (also called garbage collection) will completely remove this data on memory.

Today's article has provided you with basic knowledge about Class and Object. To continue the topic of Object-Oriented Programming in Python, the following article, Quantrimang, will work with you to learn about Inheritance and Multi-inheritance. Invites you to read the track.

See more:

  1. Exception handling - Exception Handling in Python
  2. Working with File in Python
  3. Matrix in Python

Previous article: Object-oriented programming in Python

Next lesson: Inheritance (Inheritance) in Python

« PREV
NEXT »