Python中的扩展方法 [英] Extension methods in Python

查看:104
本文介绍了Python中的扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python是否有像C#这样的扩展方法?是否可以调用如下方法:

  MyRandomMethod()
int ?

 

p> myInt.MyRandomMethod()


解决方案

<您可以在Python代码中定义的类对象(AKA monkey patching)中添加您喜欢的任何方法:

 >> > A类(物体):
>>>通过


>>> def stuff(self):
>>>打印自己

>>> A.test = stuff
>>> A()。test()

这不适用于内建类型,因为它们的 __ dict __ 不可写(这是一个 dictproxy )。



Python中没有真正的扩展方法机制。


Does Python have extension methods like C#? Is it possible to call a method like:

MyRandomMethod()

on existing types like int?

myInt.MyRandomMethod()

解决方案

You can add whatever methods you like on class objects defined in Python code (AKA monkey patching):

>>> class A(object):
>>>     pass


>>> def stuff(self):
>>>     print self

>>> A.test = stuff
>>> A().test()

This does not work on builtin types, because their __dict__ is not writable (it's a dictproxy).

So no, there is no "real" extension method mechanism in Python.

这篇关于Python中的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆