简体   繁体   English

“class.object.function”在python中是如何实现的?

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

So in Pandas we can do str operations on a string column like所以在 Pandas 中,我们可以对字符串列进行str操作,例如

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

I wonder, how is the str.lower() implemented in a class (note it is not about the specific implementation of str.lower() but more how such a thing would be implemented in python generally)?我想知道, str.lower()是如何在一个类中实现的(注意它不是关于str.lower()具体实现,而是更多如何在 python 中实现这样的东西)?

The only thing I can think of, Is a method of a sub-class defined in the class eg我唯一能想到的,是类中定义的子类的方法,例如

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

but I doubt it's correct但我怀疑它是否正确

Since Pandas is open source, you can find the code on Github!由于 Pandas 是开源的,你可以在 Github 上找到代码! Here is the .str implementation page. 是 .str 实现页面。 The _map_and_wrap function provides a nice way of understanding what's happening, start with it and go deeper! _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

Maybe it uses property , it allows you to get the return value of a function like a attribute:也许它使用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']

The essence of property is to wrap a function into a descriptor . property的本质是将一个函数包装成一个描述符 You can consider learning about it.你可以考虑学习一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM