某些Python包如何修改/添加到其他包的方法



例如:Pandas提供了一个带有apply方法的DataFrame对象。安装另一个软件包Pandarallel为相同的Panda DataFrame对象提供了一个新的parallel_apply方法。这是如何实现的?

大多数对象都是可变的。它只是为类添加了更多的属性。

例如,

from collections import Counter
c = Counter('abc')
try:
c.foo()  # AttributeError: 'Counter' object has no attribute 'foo'
except e:
pass
c.foo = lambda: print('hello')
c.foo()  # prints hello

要获得更明确的答案,请查看源代码-https://github.com/nalepae/pandarallel/blob/master/pandarallel/pandarallel.py#L572

看起来,如果向类中添加一个方法,在此之前创建的所有对象都将具有新方法。

class A:
pass
a = A()
A.m = lambda self, x: x
# This returns 5!!
a.m(5)

虽然这似乎不是引用包中使用的技术,但一种方法是类对象可以从其他类对象继承。

因此,在一个单独的包中,您可以创建一个新的CustomDataFrame类:

from pandas import DataFrame
class CustomDataFrame(DataFrame):
"""Custom dataframe with new method"""
def new_func(self, x):
print(x)
df = CustomDataFrame()
df.new_func("new function that prints")  # --> prints "new function that prints"

CustomDataFrame将具有原始基类DataFrame的所有属性,再加上CustomDataFrame.new_func()方法。

也可以使用与基类相同的名称命名派生类,并且使用相同名称创建的新方法将覆盖基类方法。

from pandas import DataFrame
class DataFrame(DataFrame):
"""Custom dataframe with new method"""
# methods of same name will override the base class
def apply(self):
print("df.apply() overridden")
df = DataFrame()
df.apply()  # --> prints "df.apply() overridden"

相关内容

最新更新