Welcome, guest | Sign In | My Account | Store | Cart

Use these instead of abstract properties when you don't plan on the abstract attribute being implemented with a property. And you can still give your attribute a docstring!

Python, 35 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""attributes module"""

class Attribute:
    """A class attribute (non-data descriptor).

    The class provides for an initial value and a docstring.  This
    replaces putting the information in the docstring of the class.

    """

    def __init__(self, value, doc=""):
        self.value = value
        self.docstring = doc
    def __get__(self, obj, cls):
        return self
    def __getattribute__(self, name):
        if name == "__doc__":
            return object.__getattribute__(self, "docstring")
        return object.__getattribute__(self, value)


class AbstractAttribute:
    """An abstract class attribute.

    Use this instead of an abstract property when you don't expect the
    attribute to be implemented by a property.

    """

    __isabstractmethod__ = True

    def __init__(self, doc=""):
        self.__doc__ = doc
    def __get__(self, obj, cls):
        return self

Example

class A(metaclass=ABCMeta):

    GROUP = AbstractAttribute("The class's group.")
    START = Attribute(5, "The START constant!")

class B(A):

    GROUP = 1

assert B.START.value == 5
assert B().START.value == 5

class C(A): pass

C()
# fails