簡體   English   中英

“class.object.function”在python中是如何實現的?

[英]How is "class.object.function" implemented in python?

所以在 Pandas 中,我們可以對字符串列進行str操作,例如

str_lower = df["str_col"].str.lower()

我想知道, str.lower()是如何在一個類中實現的(注意它不是關於str.lower()具體實現,而是更多如何在 python 中實現這樣的東西)?

我唯一能想到的,是類中定義的子類的方法,例如

class DataFrame():
     class str():
           def lower(self):
                 return [p.lower() for p in self.column]

但我懷疑它是否正確

由於 Pandas 是開源的,你可以在 Github 上找到代碼! 是 .str 實現頁面。 _map_and_wrap函數提供了一種很好的方式來理解正在發生的事情,從它開始並深入!

def _map_and_wrap(name, docstring):
    @forbid_nonstring_types(["bytes"], name=name)
    def wrapper(self):
        result = getattr(self._data.array, f"_str_{name}")()
        return self._wrap_result(result)

    wrapper.__doc__ = docstring
    return wrapper

也許它使用property ,它允許您像屬性一樣獲取函數的返回值:

>>> class Foo:
...     def __init__(self, *args):
...         self.lst = list(args)
...     @property
...     def string(self):
...         return ' '.join(map(str, self.lst))
...
>>> f = Foo(1, 2, 3, 4, 5)
>>> f.string
'1 2 3 4 5'
>>> f.string.split()
['1', '2', '3', '4', '5']

property的本質是將一個函數包裝成一個描述符 你可以考慮學習一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM