dimanche 5 avril 2015

In Python, how to enforce an abstract method to be static on the base class?


Vote count:

1




This is the setup I want: A should be an abstract base class with a static & abstract method f(). B should inherit from A. Requirements: 1. You should not be able to instantiate A 2. You should not be able to instantiate B, unless it implements a static f()


Taking inspiration from this question, I've tried a couple of approaches. With these definitions:



class abstractstatic(staticmethod):
__slots__ = ()
def __init__(self, function):
super(abstractstatic, self).__init__(function)
function.__isabstractmethod__ = True
__isabstractmethod__ = True

class A:
__metaclass__ = abc.ABCMeta
@abstractstatic
def f():
pass

class B(A):
def f(self):
print 'f'

class A2:
__metaclass__ = abc.ABCMeta
@staticmethod
@abc.abstractmethod
def f():
pass

class B2(A2):
def f(self):
print 'f'


Here A2 and B2 are defined using usual Python conventions and A & B are defined using the way suggested in this answer. Following are some operations I tried and the results that were undesired.


With classes A/B:



>>> B().f()
f
#This should have thrown, since B doesn't implement a static f()


With classes A2/B2:



>>> A2()
<__main__.A2 object at 0x105beea90>
#This should have thrown since A2 should be a base class

>>> B2().f()
f
#This should have thrown, since B2 doesn't implement a static f()


Since neither of these approaches give me the output I want, how do I achieve what I want?



asked 1 min ago

GrowinMan

1,045






In Python, how to enforce an abstract method to be static on the base class?

Aucun commentaire:

Enregistrer un commentaire