Say you have a public method in Python whose primary purpose is to retrieve the value of an underlying data attribute (i.e. internal backing store). The method may have lazy evaluation logic, etc. A property is an example of such a method.
Then it is natural to use the same name for the method and data attribute, except for an underscore prefix for the data attribute. For example--
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
(from Python's "property" documentation)
But what are some preferred conventions if the method is for internal use and so is itself prefixed with an underscore? Prefixing the backing store with two leading underscores would invoke name mangling and so is not ideal.
Two possibilities might be--
def _get_x(self):
return self._x
def _x(self):
return self._x_
Python style says the second (appending an underscore), though, should only be used to avoid conflicts with reserved keywords.
The preferred convention is to use a single leading underscore.
This is the PEP 8 recommendation for private attributes.
See this example in the docstring for property():
>>> help(property)
Help on class property in module builtins:
class property(object)
| property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
|
| fget is a function to be used for getting an attribute value, and likewise
| fset is a function for setting, and fdel a function for del'ing, an
| attribute. Typical use is to define a managed attribute x:
| class C(object):
| def getx(self): return self._x
| def setx(self, value): self._x = value
| def delx(self): del self._x
| x = property(getx, setx, delx, "I'm the 'x' property.")
|
| Decorators make defining new properties or modifying existing ones easy:
| class C(object):
| @property
| def x(self): return self._x
| @x.setter
| def x(self, value): self._x = value
| @x.deleter
| def x(self): del self._x
|
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