I encoded a decoration (for the sake of curiosity) to create an abstract class in python. It still seemed like this would work, but I got unexpected behavior.
The design idea looks like this:
from abc import ABCMeta, abstractmethod def abstract(cls): cls.__metaclass__ = ABCMeta return cls
Then, when using this decoration, it was only necessary to determine the abstract method
@abstract class Dog(object): @abstractmethod def bark(self): pass
But when I test, I was able to instantiate the Dog object:
d = Dog() d.bark() //no errors Dog.__metaclass__ //returned "<class 'abc.ABCMeta'>"
When directly testing the __metaclass__ it behaves as expected:
class Dog(object): __metaclass__ = ABCMeta @abstractmethod def bark(self): pass
Testing:
d = Dog() "Traceback (most recent call last): File "<pyshell#98>", line 1, in <module> d = Dog() TypeError: Can't instantiate abstract class Dog with abstract methods bark"
Why is this happening?
python abstract-class
Hydren
source share