Python's equivalent for Ruby's define_method?

后端 未结 4 2023
傲寒
傲寒 2021-01-06 10:57

Is there a Python equivalent for Ruby\'s define_method, which would allow dynamic generation of class methods? (as can be seen in Wikipedia\'s Ruby example code

4条回答
  •  爱一瞬间的悲伤
    2021-01-06 11:22

    In Python, you can just set a method on a class:

    >>> class Spam:
    ...     def __init__(self, x):
    ...         self.value = x
    ...
    >>> Spam.getvalue = lambda self: self.value
    >>> ham = Spam('ham')
    >>> ham.getvalue()
    'ham'
    

    Fancier stuff is possible with decorators.

提交回复
热议问题