python - Python中的扩展方法

标签 python function extension-methods

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/

相关文章:

python - 对于每个测试用例,显示完成计划所需的最少天数。算法思想?

python - 在运行时添加、修改、删除 celery.schedules

c++ - 在类中调用函数

javascript - (扩展)更新选项卡时保存更改的值

python - 为什么字符串的startswith比in慢?

python - 如何使用 Asyncio 和 GUI 读取文件。

python - 在 Python 的 If 语句中使用 re.match

function - 确保kotlin方法是静态的,顶级的或带注释的@JvmStatic

c# - ConvertNullDate 扩展方法

kotlin - 如何在伴随对象中使用扩展函数