Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style of addressing attributes in python

This question is one of style. Since the attributes are not private in python, is it good and common practice to address them directly outside the class using something like my_obj.attr? Or, maybe, it is still better to do it via member-functions like get_attr() that is an usual practice in c++?

like image 311
freude Avatar asked Dec 08 '22 15:12

freude


2 Answers

Sounds like you want to use 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)
>>> f.m = 6
setting attribute
>>> f.m
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 may always change your design to use properties later at no cost.

like image 113
jamylak Avatar answered Dec 11 '22 05:12

jamylak


Create an instance of the class first:

myinstance = MyClass()
myinstance.attr

Otherwise you'd get an error like AttributeError: class MyClass has no attribute 'attr' when trying to do MyClass.attr

like image 26
TerryA Avatar answered Dec 11 '22 05:12

TerryA