Addressing attribute style in python

This question is one of the styles. Since attributes are not private in python, is it a good and common practice to access them directly outside the class using something like my_obj.attr ? Or maybe it is even better to do this with member functions like get_attr() , which is common practice in C ++?

+4
source share
3 answers

It looks like you want to use the properties:

 class Foo(object): def __init__(self, m): self._m = m @property def m(self): print 'accessed attribute' return self._m @m.setter def m(self, m): print 'setting attribute' self._m = m >>> f = Foo(m=5) >>> fm = 6 setting attribute >>> fm accessed attribute 6 

This is the most adaptive way to access variables, for simple use cases you do not need to do this, and in Python you can always change your design to use properties later at no cost.

+12
source

First create an instance of the class:

 myinstance = MyClass() myinstance.attr 

Otherwise, you will get an error, for example, AttributeError: class MyClass has no attribute 'attr' when trying to make MyClass.attr

+2
source

Yes, this is a common practice. If you need more control over the way you get attributes, consider using __getattribute__ and / or __getattr__ .

0
source

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


All Articles