Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute getters in python

Tags:

python

I vaguely remember learning about some sort of built-in function that would do the equivalent of

f = lambda x: x.attr

Am I just imagining this or does such a thing exist?

like image 755
Klohkwherk Avatar asked Sep 10 '11 17:09

Klohkwherk


People also ask

What are getters in Python?

Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class. Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.

What is getter () used for?

The getter method returns the value of the attribute. The setter method takes a parameter and assigns it to the attribute. Getters and setters allow control over the values. You may validate the given value in the setter before actually setting the value.

Should I use getters in Python?

Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.

What is the pythonic way to write getters and setters in python?

You can use the magic methods __getattribute__ and __setattr__ . Be aware that __getattr__ and __getattribute__ are not the same. __getattr__ is only invoked when the attribute is not found.


2 Answers

operator.attrgetter()

like image 64
Ignacio Vazquez-Abrams Avatar answered Oct 18 '22 03:10

Ignacio Vazquez-Abrams


getattr(obj, 'attr')

will get the attribute attr from obj, or raise AttributeError if it doesn't exist. You can also supply a default value:

getattr(obj, 'attr', None)

in which case the default will be returned instead of raising an exception if the attribute can not be found on the object.

like image 27
Ethan Furman Avatar answered Oct 18 '22 01:10

Ethan Furman