fizzer
fizzer

Reputation: 13806

Can/should I implement Python methods by assignment to attributes?

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

Answers (2)

Sven Marnach
Sven Marnach

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

phihag
phihag

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

Related Questions