简体   繁体   中英

python style guide by google - clarification on properties

Question

Please elaborate on the Goolge Python Stile Guide on properties:

Inheritance with properties can be non-obvious if the property itself is not overridden

ensure methods overridden in subclasses are called by the property

  1. What does non-obvious mean and what are potential issues?
  2. What does ensure overridden method to be called by property mean and what are potential issues?

Google Python Style Guide 2.13 Properties

2.13.4 Decision
Inheritance with properties can be non-obvious if the property itself is not overridden . Thus one must make sure that accessor methods are called indirectly to ensure methods overridden in subclasses are called by the property (using the template method design pattern).

import math

     class Square:
         """A square with two properties: a writable area and a read-only perimeter.

         To use:
         >>> sq = Square(3)
         >>> sq.area
         9
         >>> sq.perimeter
         12
         >>> sq.area = 16
         >>> sq.side
         4
         >>> sq.perimeter
         16
         """

         def __init__(self, side):
             self.side = side

         @property
         def area(self):
             """Area of the square."""
             return self._get_area()

         @area.setter
         def area(self, area):
             return self._set_area(area)

         def _get_area(self):
             """Indirect accessor to calculate the 'area' property."""
             return self.side ** 2

         def _set_area(self, area):
             """Indirect setter to set the 'area' property."""
             self.side = math.sqrt(area)

         @property
         def perimeter(self):
             return self.side * 4

What's non-obvious is that when you inherit from the class you have to take special consideration of how you override properties in the subclass, because the definition may be spread between multiple methods.

If you define a subclass of Square that implements the area property differently, you need to do either:

  1. Ensure that the Square._get_area() and Square._set_area() methods are never called directly, only through the property methods. Then you can define new properties in the subclass.
  2. Override the _get_area() and _set_area() methods in the subclass. Then it's not necessary to redefine the properties -- they'll be inherited normally, but will call the internal methods of the subclass.

Neither of these is complicated, but it's something extra you may have to check for when inheriting from a class with properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM