Thứ Sáu, Tháng Ba 14, 2025
spot_img
HomeLearn class and object in python

Learn class and object in python

Class in Python is an important component, commonly used when programmed. Besides the Python class, you also have Object. Here are what you need Class and Object in Python.

In the era of development of technology is increasingly important with life, programming is gradually becoming the most potential day today. There is no denying the benefits of programming products. They help people access information, study and work more easily.

Currently, you have a lot of programming language options, and Python is one of them. The reason Python is loved by easy to learn, easy to get used to and used. You can find many Python self -study guidelines on the Internet and Quantrimang.com is one of them.

Basically, Python also has many components that make up a complete program, like every other popular programming language. Class, Object is the most basic and appears almost in all programming projects. Here's how to use Class, Object in Python.

Class is a Blueprint or prototype set by users from the object created. Class provides vehicles combining data and functions together. Creating a new class means creating a new type of object, allowing the new version of that type to be created. Each Class version has the accompanying attribute to maintain its state. Class versions also have methods (defined by class) to edit their status.

To understand the need to create classes and objects in Python, let's consider the specific examples below after grasping the basic syntax and use.

Python is an object -oriented programming language. Unlike the procedure programming emphasizes the functional functions, the object -oriented programming focuses on the objects.

Object (Object) Simply a collection of data (variables) and methods (functions) works on those data. And, Class (class) is a detailed plan for the object.

We can think of the class as a sketch (prototype) of a house. It contains all the details of the floor, doors, windows, … Based on these descriptions, we will build houses. So the house here is the object.

Because many houses can be made from a description, we can create many objects from one class. An object is also called an instance (instance) of a class and the process of creating this object is called Instantiation.

See also: Learn about class, object and instance in object -oriented programming

Class declaration

Like declaring functions starting with a keyword DEF Then declare the class in Python using the keyword Class.

The first character line is called docstring – A brief description of class. Docstring This is not required but encouraged to use.

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

This is a simple way to declare the class.

Class creates a new Namespace local to become a place for its attributes to be declared. Properties may be functions or data.

There are also special attributes starting with double lower bricks (__). For example: __Doc__ Will return the docstring series describing the class.

As soon as a class declares, the object in the new class will be created with the same name. This class object allows us to access different attributes as well as to initialize 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, the object in the class can be used to access different properties and create new instance 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 more careful example of creating objects including properties and 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 parameter Self, But when calling the jaw Obj.func () No need for parameter, still not having an error. Because, whenever, the object calls methods, the object will pass itself through the first parameter. Mean Obj.func () equivalent Myclass.func (OBJ)

An object is a version of the class. A class is like a Blueprint, and the version is a copy of the class with actual values. It is no longer an idea. For example, it is a real dog, 7 -year -old Pug dog. You may have many dogs to create many different versions, but without the class as a guide, you will get lost, do not know which information is required.

An object usually includes:

  • State is represented by the attributes of an object. It also reflects the attributes of an object.
  • Behavior is represented by the methods of an object. It also shows a response of an object to another object.
  • Identity has a unique name for an object and allows an object to interact with other objects.

Construction in Python

The class jaw is started with double lower bricks (__) are special functions, with special meanings.

The one is the function __init __ (). This function is called at any time when creating an object, a new variable in the class and is called the 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 additional attributes of the object can be created quickly, as in the above example, we have created a new attribute. 'New' for the object C2 And can call out immediately. However, this new attribute will not apply to the subjects that have been declared in advance C1.

Eliminate attributes and objects

The attribute of the object may be deleted by the command Del.

>>> 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 that object by using the command Del.

>>> 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 known as Garbage Collection) will completely eliminate these data on memory.

Object methods

Subjects can also contain methods – methods. The method in the object is the functions that belong to that object.

For example, create a method in Class Person by inserting a greeting and deploying function in P1:

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

  def myfunc(self):
    print("Xin chào, tên tôi là" + self.name)

p1 = Person("Quantrimang.com", 16)
p1.myfunc()

Self parameter

Self parameter is a reference to the current version of the class. It is often used to access variables that belong to that class.

It is not necessary to name it as a self. You can call it whenever you want but it must be the first parameter of any function in the class.

For example: Use from mysillyobject and ABC instead of self:

class Person:
  def __init__(mysillyobject, name, age):
    mysillyobject.name = name
    mysillyobject.age = age

  def myfunc(abc):
    print("Xin chào, tên tôi là " + abc.name)

p1 = Person("Quantrimang.com", 16)
p1.myfunc()

Today's article has provided you with basic knowledge about class and object already. To continue the topic of object -oriented programming in Python, the next article Quantrimang will join you to learn about inheritance and multiple successor. Invite readers to follow.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments