Python's equivalent for Ruby's define_method?

后端 未结 4 1994
傲寒
傲寒 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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-06 11:28

    Functions are first-class objects in Python and can be assigned to attributes of a class or an instance. One way to do the same thing as in the Wikipedia example is:

    colours = {"black": "000",
               "red": "f00",
               "green": "0f0",
               "yellow": "ff0",
               "blue": "00f",
               "magenta": "f0f",
               "cyan": "0ff",
               "white": "fff"}
    
    class MyString(str):
        pass
    
    for name, code in colours.iteritems():
        def _in_colour(self, code=code):
            return '<span style="color: %s">%s</span>' % (code, self)
        setattr(MyString, "in_" + name, _in_colour)
    
    0 讨论(0)
  • 2021-01-06 11:28

    Either look into abstract base classes:

    http://docs.python.org/library/abc.html

    or

    check the options that the 'new' (or the newer 'types') module provides to you.

    0 讨论(0)
提交回复
热议问题