Python attributes

From wikinotes
Revision as of 19:52, 21 January 2022 by Will (talk | contribs) (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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Properties

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