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++?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With