Extension methods in Python

后端 未结 6 1028
没有蜡笔的小新
没有蜡笔的小新 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:28

    not sure if that what you're asking but you can extend existing types and then call whatever you like on the new thing:

    class  int(int):
         def random_method(self):
               return 4                     # guaranteed to be random
    v = int(5)                              # you'll have to instantiate all you variables like this
    v.random_method()
    
    class int(int):
        def xkcd(self):
            import antigravity
            print(42)
    
    >>>v.xkcd()
    Traceback (most recent call last):
      File "", line 1, in 
        v.xkcd()
    AttributeError: 'int' object has no attribute 'xkcd'
    c = int(1)
    >>> c.random_method()
    4
    >>> c.xkcd()
    42
    

    hope that clarifies your question

提交回复
热议问题