Python equivalent for Ruby define_method?

Is there a Python equivalent for Ruby define_method that will dynamically generate class methods? (as seen from Wikipedia Ruby Code Example )

+4
source share
4 answers

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

 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) 
+13
source

In Python, you can simply set the method for the class:

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

Fancier features are possible with decorators .

+2
source

You simply assign the function as a new attribute for the 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 (like the lines in the Wikipedia example), you can make it even cleaner:

  Foo.printMyName = replacement_method 
0
source

Look at the abstract base classes:

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

or

check the parameters that the "new" module (or a newer type) provides you with.

-2
source

Source: https://habr.com/ru/post/1345420/


All Articles