Reputation: 13806
Is there any stylistic taboo or other downside to implementing trivial methods by assignment to class attributes? E.g. like bar
and baz
below, as opposed to the more ususal foo
.
class MyClass(object):
def hello(self):
return 'hello'
def foo(self):
return self.hello()
bar = lambda self: self.hello()
baz = hello
I find myself tempted by the apparent economy of things like this:
__str__ = __repr__ = hello
Upvotes: 6
Views: 118
Reputation: 602635
Personally, I think things like
__str__ = __repr__ = hello
are fine, but
bar = lambda self: self.hello()
is evil. You cannot easily give a lambda a docstring, and the .func_name
attribute will have the meaningless value <lambda>
. Both those problems don't occur for the first line.
Upvotes: 8
Reputation: 288270
In general, it's completely fine 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 defined format or so).
Upvotes: 4