Python docstrings

Python 教學 4 – function, object 基本 methods, DocStrings

1. function

1.1 定義 function

Python 中用 def 來定義 function,不像 JavaScript 或是 Ruby 有結尾符號,Python 中的 function 主體為下一行後所有縮排的 statements:

def test(n):
    print('Hello World')

1.2 function 中的 variables

function 在執行時會建立一個新的 symbol table,用來儲存 function 內的 local variable,而在 function 內使用一個變數時,會先從 local symbol table 開始查找,local symbol table 不存在該變數時,在往外面一層的 symbol table,直到 general symbol table (也就是 global variable – 全域變數)

1.3 function 中的 arguments

1.3.1 Default Argument Values

argument 後面加上 = 作為該 argument 的 default value

def add_two_integer(a = 1, b = 2):
    sum = a + b
    return sum

print(add_two_integer())
3

1.3.2 Positional Argument

一般常見的 argument 呼叫方式,也就是按照傳入 argument 的位置,來決定 argument 的 value:

def print_arguments(a, b):
    print(a)
    print(b)

print(print_arguments(10, 5))
10
5

1.3.2 Keyword Argument

Python 中的 function 可以使用 keyword argument,也就是在執行 function 的時候,直接指定 function 定義中 argument 的 value:

def print_arguments(a, b):
    print(a)
    print(b)

print(print_arguments(b = 5, a = 10))
10
5

1.3.3 Argument 的限制

執行 function 時:

  • keyword argument 必須在 positional argument 的後面
  • 使用 keyword argument 時,function definition 裡必須有對應的 argument
  • argument 不能被多次賦值

1.3.4 *arguments 和 **keywords

當 function definition 裡有 *arguments 時,代表可以傳入任意數量的 arguments,這些 arguments 會以 tuple 存在變數 argument 中,*arguments 後面只能放 keyword argument
當 function definition 裡有 *keywords 時,代表可以傳入任意數量的 keywords,這些 keywords 會以 dictinoary 存在變數 keywords 中

def cars(*arguments, **keywords):
    print(arguments.__class__)
    print(keywords.__class__)


cars()
<class 'tuple'>
<class 'dict'>

範例:

def cars(brand, *arguments, **keywords):
    print("This car's brand is", brand)
    for arg in arguments:
        print("This car is", arg)
    for kw in keywords:
        print(kw, ":", keywords[kw])


cars('skoda', 'handsome', 'popular', model = 'octavia', color = 'blue')
This car's brand is skoda
This car is handsome
This car is popular
model : octavia
color : blue

1.3.5 Special parameters – /, *

argument 中有兩個特殊的 parameter:’/’ 和 ‘*’,用來決定前後的 argument 為 positional argument 或是 keyword argument:

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
      -----------    ----------     ----------
        |             |                  |
        |        Positional or keyword   |
        |                                - Keyword only
         -- Positional only

範例:

def standard_arg(arg):
    print(arg)

standard_arg(2)
2

standard_arg(arg=2)
2


def pos_only_arg(arg, /):
    print(arg)

pos_only_arg(1)
1

pos_only_arg(arg=1)
TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg'


def kwd_only_arg(*, arg):
    print(arg)

kwd_only_arg(3)
TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given

kwd_only_arg(arg=3)
3


def combined_example(pos_only, /, standard, *, kwd_only):
    print(pos_only, standard, kwd_only)

combined_example(1, 2, 3)
TypeError: combined_example() takes 2 positional arguments but 3 were given

combined_example(1, 2, kwd_only=3)
1 2 3

combined_example(1, standard=2, kwd_only=3)
1 2 3

combined_example(pos_only=1, standard=2, kwd_only=3)
TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only'

1.4 function annotations – 函數註釋

function annotations 是選擇性的 metadata,會以 dictionary 的形式存放在 function 的 __annotations__ 中。

使用方法是在 parameter 後加上 : 並加上 parameter 的 type,return 則是在 def statement 和 : 中間加上 -> ,後面再放上 return 的 type

def cars(brand: str, count: int) -> str:
    print('Annotations:', cars.__annotations__)
    return brand
cars('skoda', 10)
Annotations: {'brand': <class 'str'>, 'count': <class 'int'>, 'return': <class 'str'>}

2. 基本 Object 介紹

Python 是一個 OOP 語言,幾乎所有東西都是由 object 組成的,接下來介紹一些常用的 method

2.1 __class__

__class__ 可以用來存取該 object 是由哪個 class new 出來的:

var = 'Hello'
print(var.__class__)
<class 'str'>

var = 10
print(var.__class__)
<class 'int'>

var = 10.5
print(var.__class__)
<class 'float'>

var = 10+3j
print(var.__class__)
<class 'complex'>

var = True
print(var.__class__)
<class 'bool'>

var = False
print(var.__class__)
<class 'bool'>

var = [1, 2]
print(var.__class__)
<class 'list'>

var = (1, 2)
print(var.__class__)
<class 'tuple'>

var = range(2)
print(var.__class__)
<class 'range'>

var = {'name': 'hello'}
print(var.__class__)
<class 'dict'>

var = {"apple", "banana", "cherry"}
print(var.__class__)
<class 'set'>

var = frozenset({"apple", "banana", "cherry"})
print(var.__class__)
<class 'frozenset'>

var = None
print(var.__class__)
<class 'NoneType'>

var = b"Hello"
print(var.__class__)
<class 'bytes'>

var = bytearray(5)
print(var.__class__)
<class 'bytearray'>

var = memoryview(bytes(5))
print(var.__class__)
<class 'memoryview'>

2.2 __base__

用來存取目前 class 是由哪個 class 繼承下來的:

var = 'Hello'
print(var.__class__)
<class 'str'>
print(var.__class__.__base__)
<class 'object'>

2.3 dir()

用來存取 object 中的所有 attributes

var = 'Hello'
print(dir(var))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

2.4 __name__

可以用 __name__ 來拿到 class 或 function 的名字:

var = True
print(var.__class__)
<class 'bool'>
print(var.__class__.__name__)
bool

def test():
    print('hi')
print(test.__class__)
<class 'function'>
print(test.__class__.__name__)
function

3. DocStrings (Documentation Strings) – 說明文件字串

通常會用在 class, function, module 等等,用來描述這個 object 的功能及定義。

3.1 潛規則

通常會有幾個潛規則:

  • 第一行為說明此 object 的摘要,以大寫字母開頭,句號結尾
  • DocStrings 為多行時,第二行應為空白,目的是為了將摘要與其餘描述分開
  • 如果有 argument 和 return value,可以在第一個非空白行後描述
def add_two_integer(a, b):
    '''Returns the sum of two integer.

    Parameters:
        a (int): An integer
        b (int): Another integer

    Returns:
        sum (int): sum of a and b
    '''
    sum = a + b
    return sum

3.2 存取 DocStrings

可以用 object.__doc__ 或是 help(object) 來 access docStrings

print(add_two_integer.__doc__)
Returns the sum of two integer.

    Parameters:
        a (int): An integer
        b (int): Another integer

    Returns:
        sum (int): sum of a and b

help(add_two_integer)

4. 參考資料

Python Docstrings (With Examples) – Programiz
4. More Control Flow Tools — Python 3.11.4 documentation
How to get the parents of a Python class? – Stack Overflow
Python Data Types – W3Schools
Finding what methods a Python object has – Stack Overflow

如果覺得我的文章有幫助的話,歡迎幫我的粉專按讚哦~謝謝你!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top