Extension methods in Python

后端 未结 6 980
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 01:55

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

MyRandomMethod()

on existing types like int?

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 02:47

    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.

提交回复
热议问题