Python attributes

From wikinotes
Revision as of 01:24, 23 January 2022 by Will (talk | contribs) (→‎Properties)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


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 = value

cached

You can memoize/cache properties

import functools

class PeanutButter:
    @functools.cached_property
    def brand(self):
        return 'no-name'