Table of Contents
This guide covers learn class and object in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
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.
You 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 = 10def func(self):print('Xin chào')# Output: 10print(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
How to 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 = 10def func(self):print('Xin chào')ob = MyClass()# Output:print(MyClass.func)# Output: >print(ob.func)#G?i hàm func()# Output: Xin chàoob.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 = rself.phanao = idef getData(self):print("{}+{}j".format(self.phanthuc,self.phanao))# T?o ??i t??ng s? ph?c m?ic1 = SoPhuc(2,3)# G?i hàm getData()# Output: 2+3jc1.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.
How to 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>>> c1Traceback (most recent call last):.NameError: name 'c1' is notdefined
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, TipsMake, will work with you to learn about Inheritance and Multi-inheritance. Invites you to read the track.
Previous article: Object-oriented programming in Python
Next lesson: Inheritance (Inheritance) in Python
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.