Python's equivalent for Ruby's define_method?

后端 未结 4 1995
傲寒
傲寒 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:23

    You just assign a function as a new attribute to a class:

     def replacement_method(self):
         print self.name
    
    
     class Foo(object):
         def __init__(self, name):
             self.name = name
         # .... whatever
    
     setattr(Foo, "printMyName", replacement_method) # assign it
     Foo("Joe").printMyName() # call it
    

    If you don't need a computable name (as are strings in the sample from Wikipedia), you can have it even cleaner:

     Foo.printMyName = replacement_method
    

提交回复
热议问题