Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 561
fizzer Avatar asked Jun 05 '11 16:06

fizzer


People also ask

Can methods have attributes in Python?

A method could also utilize the attributes that you defined within the object itself. Another key difference between a method and attribute is how you call it. For example, let's say we create an instance using the above class we defined. Save this answer.

What is the difference between attributes and methods in Python?

Attributes of a class are function objects that define corresponding methods of its instances. They are used to implement access controls of the classes. Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object.

How do you assign a value to an attribute in Python?

Python setattr() method is used to assign the object attribute its value.

What is a used to access the attributes and methods of the class in Python?

getattr() − A python method used to access the attribute of a class.


1 Answers

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.

like image 161
Sven Marnach Avatar answered Oct 01 '22 17:10

Sven Marnach