Reputation: 2068
My question is almost identical to this one, but it looks like a dead thread and the question I want to ask looks a little buried.
Question: if I want to use @property
to make private attributes, what should I name the underlying variable?
Code:
# I want to replace "NAME" with something.
class MyClass(object):
def __init__(self, x):
self.NAME = x
@property
def _x(self):
validate_x_get()
return self.NAME
@_x.setter
def _x(self, val):
validate_x_set(val)
self.NAME = val
...
Explanation: I want to use @property
and @valname.setter
to allow MyClass
methods to nicely work with self.NAME
. Answers to the linked question generally say to just make private getters and setters, but it feels like there should be a better way.
Discussion:
NAME
would be _x
but that would make self._x
recurse infinitely. x
would be public which is not what I want.__x
seems like a misuse of mangling which is for preventing subclassing problems. _x_private
, _stored_x
, _my_x
are all unpleasant. Any suggestions?
Upvotes: 0
Views: 915
Reputation: 2068
Just to sum up the discussion:
In that spirit, I'll be advocating for _x_
in my codebases (fewest additional characters). Thanks to all the commenters.
Upvotes: 3