Can / should I implement Python methods by assigning attributes?

Is there a stylistic taboo or other flaw for implementing trivial methods by assigning class attributes? For instance. for example, bar and baz lower, in contrast to the more significant foo .

 class MyClass(object): def hello(self): return 'hello' def foo(self): return self.hello() bar = lambda self: self.hello() baz = hello 

I am tempted by the obvious savings of such things:

 __str__ = __repr__ = hello 
+6
source share
2 answers

Personally, I think things like

 __str__ = __repr__ = hello 

are accurate but

 bar = lambda self: self.hello() 

- evil. You cannot give lambda a docstring easily, and the .func_name attribute will have a meaningless <lambda> value. Both of these problems do not occur for the first line.

+8
source

In general, it is normal to assign methods to other names. However, in many cases, hello should have been __str__ in the first place (unless hello returns a string in a specific format or so).

+4
source

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


All Articles