Extension methods in Python

后端 未结 6 966
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  囚心锁ツ
    2021-01-31 02:49

    It can be done with Forbidden Fruit (https://pypi.python.org/pypi/forbiddenfruit)

    Install forbiddenfruit:

    pip install forbiddenfruit
    

    Then you can extend built-in types:

    >>> from forbiddenfruit import curse
    
    >>> def percent(self, delta):
    ...     return self * (1 + delta / 100)
    
    >>> curse(float, 'percent', percent)
    >>> 1.0.percent(5)
    1.05
    

    Forbidden Fruit is fundamentally dependent on the C API, it works only on cpython implementations and won’t work on other python implementations, such as Jython, pypy, etc.

提交回复
热议问题