Python attributes: Difference between revisions
From wikinotes
(Created page with " = Properties = <blockquote> Properties are public attributes whose return value is determined by a method.<br> By default they are read-only, but you can also use them to va...") |
|||
Line 2: | Line 2: | ||
= Properties = | = Properties = | ||
<blockquote> | |||
== basics == | |||
<blockquote> | <blockquote> | ||
Properties are public attributes whose return value is determined by a method.<br> | Properties are public attributes whose return value is determined by a method.<br> | ||
Line 21: | Line 23: | ||
self._brand = value | self._brand = value | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- basics --> | |||
== cached == | |||
<blockquote> | |||
You can memoize/cache properties | |||
<syntaxhighlight lang="python"> | |||
import functools | |||
class PeanutButter: | |||
@functools.cached_property | |||
def brand(self): | |||
return 'no-name' | |||
</syntaxhighlight> | |||
</blockquote><!-- cached --> | |||
</blockquote><!-- Properties --> | </blockquote><!-- Properties --> |
Latest revision as of 01:24, 23 January 2022
Properties
basics
Properties are public attributes whose return value is determined by a method.
By default they are read-only, but you can also use them to validate types on assignment.class PeanutButter: def __init__(self): self._brand = 'skippy' @property def brand(self): return self._brand @name.setter def brand(self, value): if value not in ('skippy', 'kraft', 'jif'): raise ArgumentError("Is that even peanut butter?") self._brand = valuecached
You can memoize/cache properties
import functools class PeanutButter: @functools.cached_property def brand(self): return 'no-name'