Reputation: 31
OK Hear me out. I know that it is convention to start attribute names with an underscore when they shouldn't be accessed directly.
However I see some disadvantages to following this convention when using getters and setters in Python. Consider the following example:
class TestClass:
def __init__(self, test_param):
self._test_attr = test_param
@property
def test_attr(self):
return self._test_attr
@test_attr.setter
def test_attr(self, value):
self._test_attr = value.upper()
test_instance = TestClass("foo")
print(test_instance.test_attr)
The setter-method isn't called, when the attribute is set during the initialization. This is obviously bad, because the attribute is always supposed to be uppercase in this example.
Now consider this example where I break with convention and the name of my attribute doesn't start with an underscore:
class TestClass:
def __init__(self, test_param):
self.test_attr = test_param
@property
def test_attr(self):
return self._test_attr
@test_attr.setter
def test_attr(self, value):
self._test_attr = value.upper()
test_instance = TestClass("foo")
print(test_instance.test_attr)
In this example the setter-method is called during the initialization and thus I can expect a consistent "handling" of the attribute whether it's during or after the initialization of the object.
However this approach makes the code less clear and a different developer looking at my code might not see that the attribute is supposed to be non-public.
Both solutions aren't optimal in my opinion. What is the common practice? Is there a way where I can get the best of both worlds?
Thanks in advance.
Upvotes: 0
Views: 72