freude
freude

Reputation: 3832

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++?

Upvotes: 4

Views: 190

Answers (3)

boobookum
boobookum

Reputation: 113

Yes, it is a common practice. If you want greater control over the way the attributes are retrieved, consider using __getattribute__ and/or __getattr__.

Upvotes: 0

jamylak
jamylak

Reputation: 133504

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.

Upvotes: 12

TerryA
TerryA

Reputation: 59974

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

Upvotes: 2

Related Questions