Python 有没有像 C# 这样的扩展方法?是否可以调用如下方法:
MyRandomMethod()
在 int
等现有类型上?
myInt.MyRandomMethod()
最佳答案
您可以在 Python 代码中定义的类对象上添加任何您喜欢的方法(AKA 猴子补丁):
>>> class A(object):
>>> pass
>>> def stuff(self):
>>> print self
>>> A.test = stuff
>>> A().test()
这不适用于内置类型,因为它们的 __dict__
是不可写的(它是一个 dictproxy
)。
所以不,Python 中没有“真正的”扩展方法机制。
关于python - Python中的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/514068/