例如:熊猫提供了一个DataFrame对象和apply方法。安装另一个软件包Pandarallel为相同的熊猫DataFrame对象提供了一个新的parallel_apply方法。这是如何实现的?
发布于 2021-12-16 20:57:10
大多数对象是可变的。它只是向类添加了更多的属性。
例如,
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。
发布于 2021-12-16 21:25:46
看起来,如果将方法添加到类中,那么在此之前创建的所有对象都将具有新的方法。
class A:
pass
a = A()
A.m = lambda self, x: x
# This returns 5!!
a.m(5)发布于 2021-12-16 21:56:13
虽然它似乎不是引用包中使用的技术,但有一种方法是类对象可以从其他类对象继承。。
因此,在一个单独的包中,您可以创建一个新的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"https://stackoverflow.com/questions/70385472
复制相似问题