+14

Học Python từ con số 0 (Phần 1) - The Basics

Trước tiên, Python là gì ? Theo người tạo ra ngôn ngữ này, Guido van Rossum, Python là một:

“high-level programming language, and its core design philosophy is all about code readability and a syntax which allows programmers to express concepts in a few lines of code.”

Đối với tôi, lý do đầu tiên để học lập trình Python là nó thực sự là một ngôn ngữ tuyệt vời. Nó thực sự gần gũi khi code và thể hiện suy nghĩ của mình. Một lý do khác là chúng ta có thể sử dụng mã hóa bằng Python theo nhiều cách như data science, web development and machine learning

The Basics

1. Variables Trong các ngôn ngữ lập trình khác, biến để lưu trữ giá trị. Trong Python, rất dễ để khai báo biến và thiết lập giá trị cho nó. Ví dụ, bạn muốn lưu giữ số 1 trong một biến được gọi là once.

one = 1

Đơn giản như thế nào. Bạn có thể gán giá trị 1 cho biến one. Tương tự với các giá trị khác tương tự Bên cạnh integers, chúng ta có thể sử dụng booleans (True/False), string, float và nhiều kiểu dữ liệu khác

# booleans
true_boolean = True
false_boolean = False

# string
my_name = "DiepTX"

# float
book_price = 53.400

2. Control Flow: conditional statements if sử dụng một biểu thức để đánh giá điều kiện đúng hay sai, nếu nó là True, nó thực hiện những gì bên trong câu lênh if. Ví dụ:

if True:
  print("Hello Python If")
if 2 > 1:
  print("2 is greater than 1")

Khối else sẽ được thực thi nếu điều kiện trong if là sai

if 1 > 2:
  print("1 is greater than 2")
else:
  print("1 is not greater than 2")

Bạn cũng có thể sử dụng khối elif

if 1 > 2:
  print("1 is greater than 2")
elif 2 > 1:
  print("1 is not greater than 2")
else:
  print("1 is equal to 2")

3. Loop Trong Python, bạn có thể lặp lại trong nhiều hình thức khác nhau. Tôi sẽ nói về whilefor Vòng lặp while: Trong khi điều kiện là True, code bên trong khối sẽ được thực hiện

num = 1
while num <= 10:
  print(num)
  num += 1

Vòng lặp while cần một điều kiện lặp. Nếu nó vẫn đúng, vẫn tiếp tục lặp. Trong ví dụ trên, khi num11 điều kiện lặp sẽ là False Vòng lặp for: bạn có thể đưa biến num vào trong khối và khối for sẽ thực hiện lặp

for i in range(1, 11):
    print(i)

List: Collection | Array | Data Structure

Bạn muốn lưu trữ số nguyên 1 trong một biến, nhưng giờ muốn lưu 2, 3, 4 hoặc nhiều hơn? List là một collection mà bạn có thể sử dụng để lưu trữ một danh sách các giá trị

my_integers = [1, 2, 3, 4, 5]

Và việc lấy ra các phần tử trong list cũng giống như các ngôn ngữ lập trình khác đó là thông qua các index của danh sách

my_integers = [1, 2, 3, 4, 5]
print(my_integers[0]) # => 1
print(my_integers[3]) # => 4

Dictionary: Key-Value Data Structure

Với Lists được đánh index là các integer. Nhưng nếu không muốn sử dụng integer là index? Một cấu trúc dữ liệu mà ta có thể sử dụng là số, chuỗi hoặc các loại chỉ số khác Cấu trúc dữ liệu với tên gọi Dictionary khá giống trong Swift đó nhé 😁. Dictionary là một collection của cặp key-value

dictionary_example = {
    "key1": "value1",
    "key2": "value2"
}

key là chỉ số trỏ tới value. Làm thế nào để truy cập tới value của Dictionary. Thông qua sử dụng key nhé.

dictionary_acc = {
    "name" = "Diep",
    "age" = 23
}

print("My name is %s " %(dictionary_acc["name"])) # My name is Diep
print("I'm %i " %(dictionary_acc["age"])) # I'm 23

Lặp qua cấu trúc dữ liệu

Lặp trong List rất đơn giản.

bookshelf = [
  "The Effective Engineer",
  "The 4 hours work week",
  "Zero to One",
  "Lean Startup",
  "Hooked"
]
for book in bookshelf:
    print(book)

Với cấu trúc dữ liệu Dictionary. Cũng có thể sử dụng for nhưng với key:

dictionary = {"some_key": "some_value"}
for key in dictionary:
    print("%s ---> %s" %(key, dictionary[key]))
# some_key ---> some_value

Có một cách khác đó là sử dụng items

dictionary = { "some_key": "some_value" }
for key, value in dictionary.items():
    print("%s ---> %s" %(key, value))
# some_key ---> some_value

Class và Object

Object là một đại diện của đối tượng thực tế như xe, nhà, chó, méo. Đối tượng chia sẻ hai đặc điểm chính: DataBehavior Xe có data như số bánh xe, số ghế... và có behavior có thể chạy, dừng lại, hiển thị xăng và nhiều thứ khác Chúng ta nhận định rằng data giống như attributesbehavior giống như methods trong lập trình hướng đối tượng Data -> Attibutes and Behavior -> Methods Và Class là một bản thiết kế chi tiết từ các đối tượng được tạo ra. Trong thế giới thực chúng ta có nhiều kiểu đối tượng giống nhau, tất cả chúng có chung 1 sản phẩm mẫu (đều có động cơ, bánh xe, cửa ra vào)...

Lập trình hướng đối tượng trong Python

Khai báo class

class Vehicle:
    pass

Object là một thể hiện của class.

car = Vehicle()
print(car) # <__main__.Vehicle instance at 0x7fb1de6c2638>

car là một object (hoặc instance) của class Vehicle Ở ví dụ trên, lớp Vehicle có 4 thuộc tính: number of wheels, type of tank, seating capacity, và maximum velocity. Chúng ta đặt cho tất cả các thuộc tính này khi tạo một object vehicle. Ở đây chúng ta khai báo class để nhận data khi nó được khởi tạo:

class Vehicle:
     def _init_(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity 

Sử dụng phương thức init, gọi tới một phương thức khởi tạo. Khi tạo ra object vehicle, các attributes được khởi tạo. Tất cả thuộc tính được set. Nhưng truy cập vào giá trị của chúng bằng cách nào ?

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

    def number_of_wheels(self):
        return self.number_of_wheels

    def set_number_of_wheels(self, number):
        self.number_of_wheels = number

Implement 2 phương thức number_of_wheelsset_number_of_weels. Chúng ta gọi tới gettersetter. Trong Python, sử dụng @property (decorators) để khai báo getters and setters

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

    @property
    def number_of_wheels(self):
        return self.number_of_wheels

    @number_of_wheels.setter
    def number_of_wheels(self, number):
        self.number_of_wheels = number

Và có thể sử dụng các method này như một attributes


tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2
print(tesla_model_s.number_of_wheels) # 2

Tính đóng gói: Hiding Information

Public Instance Varibales

Class của Python có thể khởi tạo public instance variable

class Person:
    def __init__(self, first_name):
        self.first_name = first_name

Sử dụng giá trị first_name là một đối số public instance variable

tk = Person('TK')
print(tk.first_name) # => TK

Non-public Instance Variable

We don’t use the term “private” here, since no attribute is really private in Python (without a generally unnecessary amount of work). — PEP 8

Giống như public instance variable, chúng ta có thể khai báo none-public instance variable vả trong phương thức khởi tạo hoặc trong class. Sự khác biệt cú pháp là: đối với none-public instance variables sử dụng gạch dưới trước variable.

‘Private’ instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member)” — Python Software Foundation

Ví dụ:


class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name
        self._email = email

Bạn có thấy biến email? Đây là cách ta xác định một biến none-public

tk = Person('TK', 'tk@mail.com')
print(tk._email) # tk@mail.com

We can access and update it. Non-public variables are just a convention and should be treated as a non-public part of the API.

Do đó chúng ta sử dụng một phương pháp cho phép làm điều đó trong khai báo lớp. Implement 2 method (emailupdate_email)

class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name
        self._email = email

    def update_email(self, new_email):
        self._email = new_email

    def email(self):
        return self._email

Như trên chúng ta có thể cập nhật và truy cập non-public variables sử dụng các method đó

tk = Person('TK', 'tk@mail.com')
print(tk.email()) # => tk@mail.com
tk._email = 'new_tk@mail.com'
print(tk.email()) # => tk@mail.com
tk.update_email('new_tk@mail.com')
print(tk.email()) # => new_tk@mail.com
  1. Khởi tạo 1 object mới với first_name TK and email tk@mail.com
  2. In ra email bằng cách truy cập non-public variable với một method
  3. Cố gắng để set một email mới trong lớp
  4. Cần đối xử với non-public varible như một phần non-public của API
  5. Cập nhật non-public varible với phương thức khởi tạo
  6. Ta có thể update nó trong class với helper method

Public method

Với public method

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

    def show_age(self):
        return self._age

Và cũng không ngoại lệ đối với Python hay các ngôn ngữ lập trình khác

tk = Person('TK', 25)
print(tk.show_age()) # => 25

Non public method

Nhưng với non-public method ta không thể gọi như public method . Cùng sử dụng class Person nhưng với non-public method với dấu gạch dưới _

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

    def _show_age(self):
        return self._age

Ta sẽ gọi method đó như sau

tk = Person('TK', 25)
print(tk._show_age()) # => 25

We can access and update it. Non-publicmethods are just a convention and should be treated as a non-public part of the API.

Dưới đây là ví dụ để ta hiểu rõ hơn về nó

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

    def show_age(self):
        return self._get_age()

    def _get_age(self):
        return self._age

tk = Person('TK', 25)
print(tk.show_age()) # => 25

Chúng ta có show_agepublic method_get_agenon-public method. show_age có thể sử dụng bởi class Person_get_age chỉ được sử dụng bên trong class đã khai báo (bên trong show_age) Với tính kế thừa cũng giống như các ngôn ngữ lập trình hướng đối tượng khác nên tôi sẽ không đề cập ở bài viết này nữa. Ở bài viết sau tôi sẽ đi sâu hơn về ngôn ngữ Python. Cảm ơn bạn đã đọc bài viết này ! To be continue...


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí