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.
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:
- Exception handling - Exception Handling in Python
- Working with File in Python
- Matrix in Python
Previous article: Object-oriented programming in Python
Next lesson: Inheritance (Inheritance) in Python
You should read it
May be interested
- Inheritance (Inheritance) in Pythoninheriting in object-oriented programming allows us to declare new classes to re-use the parent class's functions and attributes and extra functions. in this article, we will learn how to use legacy in python.
- Multiple Inheritance in Pythoninheritance allows us to declare the new class to re-use the parent class's functions and attributes and extra functions. in this article, quantrimang will continue the lesson with the theme inheritance but at a deeper level, which is the inheritance and the order of method access of the parent classes (method resolution order).
- Programming blockchain part 3: Python programming languageguido van rossum, a dutch programmer, created python in 1991. python is based on a simple philosophy: minimalist. one of the interesting things about python is that it combines simplicity into a programming language by using spaces to denote code blocks instead of curly braces or keywords.
- Stack operator in Pythonyou can change the meaning of the operator in python depending on the operand used and we call that operator overloading. quantrimang will learn more about this content through the article. invites you to read the track.
- Complex () function in Pythonin python, the complex () function returns a complex number when the user provides a virtual and real part, or turns a string into a complex number. how does the complex () function syntax, what parameters do it have, and how is it used? invites you to read the track.
- The compile () function in Pythonthe compile () function returns a code object in python from the specified source. so how to use compile () function? please find out in this article.