Consider the following Python class. I want to set the attr
property of class A
internally, which method is the preferred way? I do not want to implement the property setter method because the user of the class should not be allowed to alter the attribute.
class A:
''' Library code '''
def __init__(self):
self._attr = None
@property
def attr(self):
return self._attr
# first approach
def _set_attr(self, data):
# Set the underlying private attribute
self._attr = data
# second approach
def _set_attr2(self, data):
# This calls __setattr__() of the base class
setattr(self, '_attr', data)
# third approach
def _set_attr3(self, data):
# Assignes data directly to the instance attribute
self.__dict__['_attr'] = data
def sets_attr(self):
''' does calculations and only calls the setter when
result is fulfilling some requirements. '''
class B(A):
''' User code - extend on library code
User can set any attribute name except the protected name 'attr'
'''