开发者

In Python, what is a preferred naming convention for the backing store of an internal property?

开发者 https://www.devze.com 2022-12-18 21:27 出处:网络
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 p

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
 |  


Why would you make it a property if it is for internal use? If it's for internal use, just access the attribute directly.

But then you would still use one underscore, but call it something else. But again, the whole point of making it a property is lost in this case.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号