You are on page 1of 26

Object-Oriented Python

OBJECT-ORIENTED PYTHON
Contents
1. Introduction ......................................................................................................... 1
2. Classes and Objects ............................................................................................. 3
3. Defining a Class .................................................................................................. 5
4. Instantiating a Class ............................................................................................ 7
5. Creating Methods ................................................................................................ 9
6. Understanding "Self'" ........................................................................................ 12
7. Creating a Method that Accepts an Argument.................................................. 15
8. Attributes and the Init Method .......................................................................... 18
9. Creating an Append Method ............................................................................. 22
10. Creating and Updating an Attribute ............................................................... 24

Tên-mssv Phân công

Trần Đức Hiếu – 20139074 1,2,5,10

Phạm Thanh Hà – 20139073 3,4,7

Phan Tấn Đạt – 20139062 6,8,9

1. Introduction

Procedural programming involves writing code in a number of sequential steps;


sometimes we combine these steps into commands called functions.
In this lesson, we're going to learn about a new system: object-oriented programming
(OOP). Rather than designing code around sequential steps, we will design it around
objects. For now, consider objects to be closely related to variables. We'll learn a more
formal definition on the next screen.

Here are a few takeaways you can expect by the end of the lesson:
- How object-oriented programming relates to the data science workflow
- Key concepts, including classes, instances, attributes, and methods
- How to create your own class

© Aptech Ltd. 1
Object-Oriented Python
When working with data, it's much more common to use a style that is closer to
procedural programming style than OOP, but it's very important to understand how
OOP works, because Python is an object-oriented language.

Khi học cách làm việc với dữ liệu bằng python, bạn sẽ gặp các objects mọi nơi
This means almost everything in Python is actually an object; when you're working
with Python, you are creating and manipulating objects. As you continue to learn to
work with data in Python, you'll encounter objects everywhere:
 NumPy and pandas — the two libraries essential to working with data in
Python: both define a number of their own object types
 Matplotlib — which you use to create data visualizations: uses object types to
define the charts you create
 Scikit-learn — which you use to create machine learning models: uses object
types to represent the models you train and use to make predictions

While it's much less common for data scientists and data analysts to define new types
of objects, we'll be using objects all the time

In OOP, objects have types, but instead of "type" we use the word class. Here are the
correct names for each of these classes:
Trong OOP, các đối tượng có nhiều kiểu khác nhau, mỗi kiểu là một class, các class đó
là:
 String class
 List class
 Dictionary class

In everyday English, the word class refers to a group of similar things. In OOP, we use
the word similarly — a class is a type of object.
Trong suốt bài học này, chúng ta sẽ sử dụng "class" khi chúng ta tìm hiểu về OOP.
When talking about programming, we often use the words "type" and "class"
interchangeably, but "class" is more formally about objects. Throughout this lesson,
we'll be using "class" as we learn about OOP.

Làm một bài khởi động nhanh, sử dụng hàm type() để trả về kiểu dữ liệu của biến
Let's do a quick exercise using the type() function to return variable types.

© Aptech Ltd. 2
Object-Oriented Python

Hàm type() sẽ trả về kiểu dữ liệu của biến đã truyền vào nên output sẽ hiện kiểu dữ liệu

2. Classes and Objects


Khi sử dụng hàm type () trên màn hình trước, nó trả về các giá trị có nhãn "class":
When we used the type() function on the previous screen, it returned values labeled
"class":

Điều này cho thấy ta có thể sử dụng ‘type’ và ‘class’ thay thế cho nhau
This demonstrates how we can use "type" and "class" interchangeably. This reveals that
we've been using classes for some time already:

© Aptech Ltd. 3
Object-Oriented Python

 Python lists là các đối tượng của class list


 Python strings là các đối tượng của str class
 Python dictionaries là các đối tượng của dict class

In this lesson, we're going to learn how classes work by creating one of our own. We're
going to create a simple class called MyList and recreate some of the basic functionality
of the Python list class.
Chúng ta sẽ tạo một class đơn giản tên là MyList và thực hiện một một số chức năng
cơ bản của class trong Python

As we mentioned earlier, it's less common for data scientists and data analysts to define
new types of objects, but understanding how objects work will be extremely valuable
to you as you continue to extend your Python knowledge and work more with objects.
Như chúng tôi đã đề cập trước đây, các nhà phân tích dữ liệu ít phổ biến hơn
khi nói đến các loại đối tượng mới, nhưng hiểu các đối tượng sẽ cực kỳ có giá
trị như thế nào đối với bạn khi bạn tiếp tục mở rộng kiến thức Python của bạn và làm
việc nhiều hơn với các đối tượng.

Before we begin, let's learn more about objects and classes. Earlier, we said that an
object is similar to a variable. As with "class" and "type," we use the two terms
interchangeably. We'll learn the subtle difference between objects and variables later,
but for now, let's look at the relationship between objects and classes:
Trước khi bắt đầu, hãy tìm hiểu thêm về các đối tượng và class. Chúng ta đã
nói trước đó rằng một đối tượng tương tự như biến. Đối với "class" và "type", chúng tôi
sử dụng hai thuật ngữ thay thế cho nhau. Chúng tôi sẽ đề cập đến sự khác biệt nhỏ giữa
các đối tượng và biến sau, nhưng bây giờ, hãy xem xét mối quan hệ giữa các đối tượng
và các class:

An object is an entity that stores data.


An object's class defines specific properties that objects of that class will have.
One way to understand the difference between a class and an object in Python is by
comparing them to real-world objects. We'll compare Python string objects to Tesla
electric cars.
Đối tượng là một thực thể lưu trữ dữ liệu. Class của một đối tượng xác định các
thuộc tính cụ thể mà các đối tượng của lớp đó sẽ có.Một cách để hiểu sự khác biệt
© Aptech Ltd. 4
Object-Oriented Python
giữa một lớp và một đối tượng trong Python là so sánh chúng với các đối tượng trong
thế giới thực. Chúng tôi sẽ so sánh các đối tượng chuỗi Python với xe điện Tesla.

There are hundreds of thousands of Tesla cars around the world. Each car is similar in
that it is a Tesla — it's not a Ford or Toyota — but at the same time, it is not necessarily
identical to other Teslas. We would say that each of the cars are objects that belong to
the Tesla class.
Có hàng trăm nghìn chiếc xe Tesla trên khắp thế giới. Mỗi chiếc xe đều giống nhau
ở chỗ nó là Tesla - nó không phải là Ford hay Toyota - nhưng đồng thời, nó không
nhất thiết phải giống với những chiếc Teslas khác. Chúng tôi có thể nói rằng mỗi
chiếc xe là những obj thuộc về class Tesla.

Tesla has a design for making their cars. The design defines what the car is, what it
does, and how it does it — everything that makes the car unique. That said, the design
isn't a car; it's just all the information necessary to create the car. Similarly, in Python,
we have designs for classes. These designs are class definitions.
Tesla có một thiết kế để sản xuất ô tô của họ. Thiết kế xác định chiếc xe là gì, nó
làm gì và nó hoạt động như thế nào - mọi thứ tạo nên sự độc đáo của chiếc xe. Điều
đó nói lên rằng, thiết kế không phải là một chiếc xe hơi; nó chỉ là tất cả thông tin cần
thiết để tạo ra chiếc xe. Tương tự, trong Python, chúng ta có các thiết kế cho các lớp.
Những thiết kế này là định nghĩa của class

3. Defining a Class
We define a class similarly to how we define a function:
Định nghĩa, đặt tên, lớp giống như làm với hàm, nhưng k có giấu ngoặc đơn()

© Aptech Ltd. 5
Object-Oriented Python

Notice that the class definition doesn't have parenthesis (). This is optional for classes,
and the convention is to not use them. Similarly, we indent the body of our class like a
function's body.

The rules for naming classes are the same as naming functions and variables:

That said, there is a convention for variables and functions in Python called Snake
Case, which uses all lowercase letters and underscores: like_this. With classes, the
convention is to use Camel Case, where no underscores appear between words, and we
capitalize the first letter of each word: LikeThis

If we try to run either of the code examples in the diagram at the top of this screen, we
will get a SyntaxError because Python doesn't let us define classes or functions when they
are empty:
We can use the pass statement to avoid this error. The pass statement doesn't do
anything, but it lets us define an empty code block. Let's see how that looks:

The pass statement is useful if you're building something complex and you want to
create a placeholder for a function that you will build out later without causing any
error. We'll use the pass statement on this screen to define an empty class without
causing an error.
Let's use what we've learned to create the very first class!
Với các lớp, quy ước là đặt tên là Camel Case không có dấu gạch dưới xuất hiện
giữa các từ và viết hoa chữ cái đầu tiên của mỗi từ: My class

Chúng ta sẽ bị lỗi cú pháp củ lớp hoặc hàm khi nó trống, có thể sử dụng câu lệnh
pass để tránh lỗi , nó cho phép xác định khối lênh trống

© Aptech Ltd. 6
Object-Oriented Python

Đoạn code khai báo một class trống và dùng lệnh pass để tránh lỗi SyntaxError
Code chạy bình thường

4. Instantiating a Class

Earlier, we compared objects to Tesla cars to help us understand the distinction between
a class and an object. Let's extend that analogy to help us understand more about classes.

Trong OOP, sử dụng instance để mô tả từng đối tượng khác nhau


In OOP, we use instance to describe each different object. Let's look at an example:

We can say the same of Python strings. We might create two Python strings, and they
can hold different values, but they work the same way:

© Aptech Ltd. 7
Object-Oriented Python

Đối tượng trong class có thể được sử dụng để truy cập các thuộc tính khác nhau và
tạo các instance mới của lớp đó. Thủ tục để tạo một đối tượng tương tự như cách ta
gọi hàm
Once we have defined our class, we can create an object of that class, which we
call instantiation. If you create an object of a particular class, the technical phrase for
what you did is to "Instantiate an object of that class." Let's learn how to instantiate an
instance of our new class:

That single line of our code actually did two things:


 Instantiated an object of the class ExampleClass
 Assigned that instance to the variable named my_class_instance

To illustrate this more clearly, let's look at an example using Python's built-in integer
class. Let's look at a simple example using the syntax int() to convert numeric values
stored as strings to integers. We'll break down the syntax into parts, which we'll read
right-to-left:
Ta đã tạo được 1 đôi tượng của class ExampleClass và gán tên là my_class_instance
Ta có thể sử dụng đối tượng và biến để thay thế nhau, nhưng có sự khác biệt khi nói
trong OOP

The syntax to the right of the assignment operator (=) instantiates the object, and the
assignment operator and variable name create the variable. This helps us understand

© Aptech Ltd. 8
Object-Oriented Python
some of the subtle differences between an object and a variable.

Keep in mind that in casual usage, we can use "object" and "variable"' interchangeably.
The distinction is usually only important if you're talking about OOP concepts like
classes.

Tạo hàm để xác định loại dữ liệu của đối tượng

5. Creating Methods
Methods có thể hiểu là cách thức thực hiện một hành động trong class, method cũng
có thể hiểu là một hàm đặc biệt trong class
In order to make our class do something, we need to define some methods. Methods
allow objects to perform actions.

Relating back to our Tesla metaphor, an object of the Tesla "class" can do things like
"unlock" and "accelerate." Similarly, Python strings have methods that can replace
substrings, convert the case of the object, and more:
© Aptech Ltd. 9
Object-Oriented Python

You can think of methods like special functions that belong to a particular class. This
is why we call the replace method str.replace()— because the method belongs to
the str class.

While we can use a function with any object, each class has its own set of methods.
Let's look at an example using some of Python's built-in classes:

List ban đầu [1,2,3] , sau khi gọi method append(4) list thành [1,2,3,4]

© Aptech Ltd. 10
Object-Oriented Python

Class string method replace() thay thế một phần tử tại một vị trí đã cho
ban đầu my_string= ‘hello’
sau khi sử dụng string.replace(‘h’,’H’)=’Hello’

Ta không thể gọi method từ class khác với class của đối tượng ta đang sử dụng.
The syntax for creating a method is almost identical to creating a function, except we
indent it within our class definition. This is how we would define a simple method:

© Aptech Ltd. 11
Object-Oriented Python

Đoạn code ban đầu là class trống, dùng lệnh pass để tránh lỗi SyntaxError
Thay thế pass trong class MyClass ban đầu bằng method mới, trả về dòng chữ “This
is my first method”
Gán biến my_instance cho kết quả mà class trả về
Code chạy và biến my_instance có giá trị là ‘This is my first method’

6. Understanding "Self'"

Định nghĩa một class, sau đó tạo một instance tên là my_instance

© Aptech Ltd. 12
Object-Oriented Python

Xảy ra lỗi khi có một đối số đã được cấp cho first method (), nhưng không cấp bất kì
đối số nào khi chạy lệnh my_instance.first_method (). Cho nên có một đối số đã được
thêm vào đâu đó

Khi ta gọi first_method() thuộc my_instance, python sẽ thêm một đối số đại diện cho
trường hợp mà ta gọi trở thành NewList.first_method(instance)

© Aptech Ltd. 13
Object-Oriented Python
Sử dụng str.title() để chuyển đổi một chuỗi bất kì thành chuỗi có chữ hoa đầu đề.

 Định nghĩa class (ExampleClass) với print_self có 1 đối số và in nó ra


 Khởi tạo mc và gắn cho class đó

Gọi mc.print_self() để so sánh với khi print(mc)

© Aptech Ltd. 14
Object-Oriented Python
Thấy sự giống nhau khi so sánh cả hai cách làm trên nên đối số ẩn này là đối tượng.
Có thể đưa ra đối số này – được truyền cho mọi phương thức – cho bất kì tham số nào.
Nhưng với tham số self là một quy ước quan trọng để định nghĩa các class, nếu không
có nó các định nghĩa sẽ trở nên khó hiểu
Sửa đổi class bằng cách thêm self làm đối số. Sau đó gọi phương thức để nó không bị
lỗi

Result:

7. Creating a Method that Accepts an Argument

On the previous screen, we learned the following:


 A "phantom" argument passes methods when we call them.
 The "phantom" argument is actually the object itself.
© Aptech Ltd. 15
Object-Oriented Python
 We need to include that in our method definition.
 The convention is to call the "phantom" argument self

The method we worked with on the previous two screens didn't accept any arguments
other than the self argument. As with functions, we often call methods with one or more
arguments so that the method can use or modify that argument.

Tạo phương thức chấp nhận một đối số chuỗi và sau đó trả về chuỗi đó. Đối số đầu
tiên sẽ luôn là chính đối tượng, chỉ định self làm đối số đầu tiên và chuỗi làm đối số
thứ hai
Let's create a method that accepts a string argument and then returns that string. The
first argument will always be the object itself, so we'll specify self as the first argument
and the string as our second argument:

Return_string trong class ExampleClass là một instance method. Về mặt hình thức
khai báo, instance method không có gì khác biệt so với một khai báo hàm thông
thường (ngoài class).
biến self là bắt buộc với mọi phương thức thành viên của Python class

-Nhưng khi ta tạo nhiều hàm với tham số self thì khởi tạo một biến với kiểu class thì
phương thức sẽ được gọi tùy thuộc vào tham số mà ta truyền vào biến.

© Aptech Ltd. 16
Object-Oriented Python

© Aptech Ltd. 17
Object-Oriented Python
8. Attributes and the Init Method
Một đối tượng thuộc "lớp" Tesla có các thuộc tính như màu sắc, pin và động cơ của
chúng. Tương tự, chuỗi Python có các thuộc tính - dữ liệu được lưu trữ bên trong chuỗi:

Bạn có thể nghĩ về các thuộc tính như các biến đặc biệt thuộc về một lớp cụ thể.
Các thuộc tính cho phép lưu trữ các giá trị cụ thể về mỗi phiên bản của lớp
Khi chúng ta khởi tạo một đối tượng, chúng ta thường chỉ định dữ liệu mà chúng ta
muốn lưu trữ bên trong đối tượng đó. Hãy khởi tạo một đối tượng int :

Khi sử dụng int () , chúng ta đã cung cấp đối số "3" , đối số này đã được chuyển đổi và
lưu trữ bên trong đối tượng. Xác định bất kỳ đối số nào chúng tôi cung cấp khi khởi tạo
bằng init
Phương thức init - còn được gọi là phương thức khởi tạo - là một phương thức đặc biệt
chạy khi chúng ta tạo một cá thể để chúng ta có thể thực hiện bất kỳ tác vụ nào để thiết
lập cá thể đó.
Phương thức init có tên bắt đầu và kết thúc bằng hai dấu gạch dưới: __init__().
Ví dụ:

© Aptech Ltd. 18
Object-Oriented Python

 Định nghĩa __init__() trong class chấp nhận hai đối số self và string

 Trong __init__(), gọi hàm print() trên đối số string

 Khi khởi tạo mc cho ExampleClass(“Hola!”). Hàm init chạy ngay lập tức hiện
thị “Hola!”
Ta hiểu rằng init có quyền truy cập vào bất kỳ đối số nào được truyền khi chúng ta khởi
tạo một đói tượng
Cách sử dụng phổ biến nhất của phương thức init là lưu trữ dữ liệu dưới dạng một thuộc
tính:

Khi chúng tôi khởi tạo đối tượng mới của mình, Python gọi phương thức init, truyền
vào đối tượng:

© Aptech Ltd. 19
Object-Oriented Python

Lưu trữ “Hola” trong thuộc tính my_attribute bên trong đối tượng. Truy cập các thuộc
tính bằng cách sử dụng dấu chấm, nhưng các thuộc tính không có dấu ngoặc đơn như
các phương thức vẫn làm. Hãy sử dụng dấu chấm để truy cập thuộc tính:

Bảng dưới đây tóm tắt một số điểm khác biệt giữa các thuộc tính và phương thức:

© Aptech Ltd. 20
Object-Oriented Python

my_list khởi tạo bằng hàm __init__ của class. Hàm __init__ sẽ được gọi ngay khi
class được gọi và gán my_list.data = initial_data.

© Aptech Ltd. 21
Object-Oriented Python
9. Creating an Append Method

Để tạo ra một phương thức chuyển đổi dữ liệu lưu trữ trong các đối tượng my_list.
Ta sẽ tạo lại chức năng của list.append() từ danh sách class python được dựng sẵn.
Ví dụ:

Để tạo phương thức này, chúng ta cần thêm một mục bổ sung vào danh sách. Một cách
đơn giản là thêm dấu ngoặc quanh mục thứ hai, làm cho nó trở thành danh sách với một
mục duy nhất, sau đó sử dụng toán tử + để nối hai danh sách đó:

Hãy nhớ rằng để truy cập thuộc tính từ bên trong, chúng ta cần sử dụng self.data, giống
như chúng ta đã làm với __init__()

© Aptech Ltd. 22
Object-Oriented Python

© Aptech Ltd. 23
Object-Oriented Python

10. Creating and Updating an Attribute


Let's summarize the work we've done so far

Right now, each behavior we've created for our MyList class is also something a regular
Python list does. Now we're going to create some new functionality: a new attribute.
When we want to find the length of a list, we use the len() function. What if we created
a new attribute, MyList.length, which stores the length of our list at all times? We can
achieve this by adding some to the __init__() method:

Let's look at what happens when we use the MyList.length attribute as defined above:

Sau khi thêm phần tử “4” vào list, nhưng attribute length vẫn không tăng thêm. Do
chúng ta định nghĩa attribute length ở init nên nó không tự cập nhật
Because the code we added that defined the length attribute was only in the init method,
if the list becomes longer using the append() method, our length attribute is no longer
accurate.
To address this, we need to run the code that calculates the length after any operation

© Aptech Ltd. 24
Object-Oriented Python
that modifies the data, which, in our case, is just the append() method. More precisely,
we need to increment the length of the list each time we append a value to it.
Để sửa lỗi chúng ta sẽ tính lại length
Let's modify the append() method so that it updates the length of the list when we use it.

© Aptech Ltd. 25
Object-Oriented Python

Ta thêm 1 lệnh là self.length+= 1 ngay khi ta append 1 phần tử mới, từ đó, attribute
length mỗi khi có phần tử mới sẽ tự động cộng thêm
Kết quả

© Aptech Ltd. 26

You might also like