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.

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

4.5 ★ | 2 Vote

May be interested

  • Zip () function in PythonZip () function in Python
    the zip () function in python returns a zip object, a list iterator of tuples that combines elements from other iterators (made of iterable words).
  • For in Python loopFor in Python loop
    in this article, we will learn more about for for loop in python as well as its variations, how to use for to repeat a string of elements in python such as list, string or other iterative objects.
  • Int () function in PythonInt () function in Python
    the int () function in python returns an integer object from any number or string.
  • Function open () in PythonFunction open () in Python
    the open () function is built into python to use to open a file and return the corresponding file object. follow the article to learn more about the syntax, parameters and usage of open ()
  • Multiple choice quiz about Python - Part 1Multiple choice quiz about Python - Part 1
    python is an object-oriented, high-level, powerful, easy-to-learn programming language. to help you read more interesting knowledge about python programming language, below the network administrator will send you a very interesting multiple choice questionnaire on this topic. please try.
  • Class member functions in C ++Class member functions in C ++
    a member function of a class is a function that has its definition or prototype inside the class definition like any other variable. it works on any object of the class that is a member, and has access to all members of a class for that object.
  • Iterator object in PythonIterator object in Python
    iterators are objects that allow us to take each of its elements, this action can be repeated. in this article, quantrimang will discuss with you how the iterator works in python and how you can build your own iterator.
  • Python data type: string, number, list, tuple, set and dictionaryPython data type: string, number, list, tuple, set and dictionary
    in this section, you'll learn how to use python as a computer, grasp python's data types and take the first step towards python programming.
  • Open source Python projects for beginnersOpen source Python projects for beginners
    where are the best open source python projects that can be learned? this is probably one of the most frequently asked questions that the 'newbie' feet wet to step into the world of python questions and learn.
  • If, if ... else, if ... elif ... else commands in PythonIf, if ... else, if ... elif ... else commands in Python
    the if statement in python is one of the most common and easy-to-learn commands. apart from if there is if else, if elif else. let's explore the details and see examples of these if commands.