Mastering Objectoriented Python
上QQ阅读APP看书,第一时间看更新

Properties versus attributes

In most cases, attributes can be set outside a class with no adverse consequences. Our example of the Hand class shows this. For many versions of the class, we can simply append to hand.cards, and the lazy computation of total via a property will work perfectly.

In cases where the changing of an attribute should lead to consequential changes in other attributes, some more sophisticated class design is required:

  • A method function may clarify the state change. This will be necessary when multiple parameter values are required.
  • A property setter may be clearer than a method function. This will be a sensible option when a single value is required.
  • We can also use in-place operators. We'll defer this until Chapter 7, Creating Numbers.

There's no strict rule. In this case, where we need to set a single parameter value, the distinction between a method function and a property is entirely one of API syntax and how well that communicates the intent.

For computed values, a property allows lazy computation, while an attribute requires eager computation. This devolves to a performance question. The benefits of lazy versus eager computation are based on the expected use cases.