Python attributes

From wikinotes



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'

    def brand(self):
        return self._brand

    def brand(self, value):
        if value not in ('skippy', 'kraft', 'jif'):
            raise ArgumentError("Is that even peanut butter?")
        self._brand = value


You can memoize/cache properties

import functools

class PeanutButter:
    def brand(self):
        return 'no-name'