Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine abc.abstractproperty with a classmethod to make an "abstract class property"?

Tags:

python

abc

I'd like to create a "class property" that is declared in an abstract base class, and then overridden in a concrete implementation class, while keeping the lovely assertion that the implementation must override the abstract base class' class property.

Although I took a look at this question my naive attempt to re-purpose the accepted answer didn't work:

>>> import abc
>>> class ClassProperty(abc.abstractproperty):
...     def __get__(self, cls, owner):
...             return self.fget.__get__(None, owner)()
...
>>> class Base(object):
...     __metaclass__ = abc.ABCMeta
...     @ClassProperty
...     def foo(cls):
...             raise NotImplementedError
...
>>> class Impl(Base):
...     @ClassProperty
...     def foo(cls):
...             return 5
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/2rs2ts/src/myproj/env/lib/python2.7/abc.py", line 94, in __new__
    value = getattr(cls, name, None)
  File "<stdin>", line 3, in __get__
TypeError: Error when calling the metaclass bases
    unbound method foo() must be called with Impl instance as first argument (got nothing instead)

I'm a little lost on what I should be doing. Any help?

like image 808
2rs2ts Avatar asked Jan 16 '15 14:01

2rs2ts


People also ask

How do you create a class property in Python?

The following example shows how to create a Circle class with a handy property to manage its radius: # circle.py class Circle: def __init__(self, radius): self. _radius = radius def _get_radius(self): print("Get radius") return self. _radius def _set_radius(self, value): print("Set radius") self.

What is Python property decorator?

The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.

What is Python @property?

The @property Decorator In Python, property() is a built-in function that creates and returns a property object. The syntax of this function is: property(fget=None, fset=None, fdel=None, doc=None)


1 Answers

You need to use this in addition to the @classmethod decorator.

class Impl(Base):
    @ClassProperty
    @classmethod
    def foo(cls):
        return 5

In [11]: Impl.foo
Out[11]: 5
like image 189
Andy Hayden Avatar answered Oct 03 '22 03:10

Andy Hayden