2015-01-16 13 views
8

Vorrei creare una "proprietà di classe" dichiarata in una classe di base astratta e quindi sovrascritta in una classe di implementazione concreta, pur mantenendo la bella asserzione che l'implementazione deve sovrascrivere la proprietà di classe della classe base astratta.Come posso combinare abc.abstractproperty con un metodo di classe per creare una "proprietà di classe astratta"?

Anche se ho preso uno sguardo al this question mio tentativo ingenuo di ri-scopo la risposta accettata non ha funzionato:

>>> 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) 

io sono un po 'perso su quello che dovrei fare. Qualsiasi aiuto?

risposta

3

È necessario utilizzare questo in aggiunta al decoratore @classmethod.

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

In [11]: Impl.foo 
Out[11]: 5 
Problemi correlati