Hướng dẫn underscore in python - gạch dưới trong python

Khi lập trình với Python, bạn thi thoảng sẽ gặp case sử dụng Single Underscore (_) và Double Underscores (__).

Vậy điều mà newbie sẽ gặp phải là sử dụng underscore như thế nào?

Bài viết này chia sẽ về cách sử dụng underscore sao cho hợp lý dựa vào:

  • Python syntax
  • Code convention

Using in interpreters

Trong Cpython và một vài Python interpreters khác, last expression value sẽ được store vào một special variable được gọi là '_'.

Exp:

$ python
Python 3.6.5 (default, Jan  9 2019, 14:12:28)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1
1
>>> _ + 2
3
>>> _ + 3
6

Ignoring the values

Giả sử ta nhận được một value là một tuple. Exmp:

>>> tuple_exm = (10, range(1, 10), "Hello")

Để lấy được

>>> tuple_exm = (10, range(1, 10), "Hello")
3 sẽ có 2 cách:

C1: Đơn giản là lấy dựa vào index.

>>> print(tuple_exm[1])
range(1, 10)

Hoặc: Nếu value nhận được mình chỉ muốn xử lý là

>>> tuple_exm = (10, range(1, 10), "Hello")
3 thì ta sẽ có cách khác:

>>> _, range_exm, _ = tuple_exm
>>> print(tuple_exm[1])
range(1, 10)

Một ví dụ khác:

for _ in range(1, 10):
    do_something()

Chốt lại,

>>> tuple_exm = (10, range(1, 10), "Hello")
5 được sử dụng để ignoring specific values nếu specific values đó không được sử dụng.

Declaring variable and function

Code convention

Using in interpreters

  • Trong Cpython và một vài Python interpreters khác, last expression value sẽ được store vào một special variable được gọi là '_'.
  • $ python
    Python 3.6.5 (default, Jan  9 2019, 14:12:28)
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 1
    1
    >>> _ + 2
    3
    >>> _ + 3
    6
    
  • Ignoring the values
  • Giả sử ta nhận được một value là một tuple. Exmp:

Để lấy được

>>> tuple_exm = (10, range(1, 10), "Hello")
3 sẽ có 2 cách:

C1: Đơn giản là lấy dựa vào index.

Hoặc: Nếu value nhận được mình chỉ muốn xử lý là

>>> tuple_exm = (10, range(1, 10), "Hello")
3 thì ta sẽ có cách khác:

  • lower_case_with_underscores

Hoặc: Nếu value nhận được mình chỉ muốn xử lý là

>>> tuple_exm = (10, range(1, 10), "Hello")
3 thì ta sẽ có cách khác:

  • UPPER_CASE_WITH_UNDERSCORES

Một ví dụ khác:

Hướng dẫn underscore in python - gạch dưới trong python
. Code bạn vẫn sẽ chạy bình thường.

Non-public

Chốt lại,

>>> tuple_exm = (10, range(1, 10), "Hello")
5 được sử dụng để ignoring specific values nếu specific values đó không được sử dụng.

Declaring variable and function

Naming Styles trong PEP8 sử dụng rất nhiều

>>> tuple_exm = (10, range(1, 10), "Hello")
5. Cụ thể là:

>>> class Parent(object):
...     def public(self):
...         pass
...     def _protected(self):
...         pass
...     def __private(self):
...         pass
...

Variable

>>> class Child(Parent):
        def method_one(self):
            pass

Method

>>> def method_one(self):
        self.public()
        self._protected()
>>> x = Child()
>>> x.method_one() # Không có lỗi

Constant

>>> def method_one(self):
        self.__private()
>>> x = Child()
>>> x.method_one()
Traceback (most recent call last):
  File "", line 1, in <module>
  File "", line 3, in method_one
AttributeError: 'Child' object has no attribute '_Child__private'

Module

_ClassName__method_name

Trích dẫn từ PEP8: https://www.python.org/dev/peps/pep-0008/

>>> def method_one(self):
        self._Parent__private()
>>> x = Child()
>>> x.method_one()

The following naming styles are commonly distinguished:

Hướng dẫn underscore in python - gạch dưới trong python
Hướng dẫn underscore in python - gạch dưới trong python
Hướng dẫn underscore in python - gạch dưới trong python
Hướng dẫn underscore in python - gạch dưới trong python

...

Tất nhiêu nếu bạn không tuân thủ code theo PEP8 thì cũng chả sao . Code bạn vẫn sẽ chạy bình thường.

Nếu như các bạn đã học Java hay C++ chắc hẳn sẽ biết về access medifiers: >>> tuple_exm = (10, range(1, 10), "Hello") 7, >>> tuple_exm = (10, range(1, 10), "Hello") 8 hay >>> tuple_exm = (10, range(1, 10), "Hello") 9. >>> print(tuple_exm[1]) range(1, 10) 0 Python không có điều đó.

Thay vào đó, những methods và instance variables non-public sẽ cần sử dụng

>>> print(tuple_exm[1])
range(1, 10)
1.

>>> tuple_exm = (10, range(1, 10), "Hello")
0

Giả sử ta có 1 class parent:

>>> tuple_exm = (10, range(1, 10), "Hello")
1

Tiếp tục tạo 1 class child extend class parent bên trên và tạo một method method_one:

Với method >>> tuple_exm = (10, range(1, 10), "Hello") 8 và >>> print(tuple_exm[1]) range(1, 10) 3 ở class parent ta dễ dàng gọi nó trong >>> print(tuple_exm[1]) range(1, 10) 4 bằng cách:

Nhưng sẽ lỗi nếu làm tương tự với method

>>> print(tuple_exm[1])
range(1, 10)
5.

Đây là câu thần chú mà bạn cần lúc này:

https://docs.python.org/3/library/gettext.html

App dụng vào ví dụ của trên của mình:

Vi diệu chưa

>>> tuple_exm = (10, range(1, 10), "Hello")
2

Avoiding conflict with Python keywords or built-ins.

Cái này có thể hiểu đơn giản là giả sử bạn muốn sử dụng từ

>>> print(tuple_exm[1])
range(1, 10)
6. Nhưng từ này phạm húy nên bạn sẽ cần chỉnh là một xíu là
>>> print(tuple_exm[1])
range(1, 10)
7 là ok

Declaring special methods