from abc import ABCMeta
class Bar:
__metaclass__ = ABCMeta
@abstractmethod
def my_abstract_method(self):
return
@abstractproperty
def my_abstract_property(self):
return
class Foo(Bar):
def my_abstract_method(self):
return
def my_abstract_property(self):
return
Bar.register(SomeRandomClass)
Setting a class's metaclass to ABCMeta
and making one of its methods
virtual makes it an ABC. A virtual method is one that the ABC says must
exist in child classes, but doesn't necessarily actually implement. There are two ways to indicate that a concrete class implements an abstract: register the class with the abstract base class or subclass directly from the abstract base class. I have done both in above example.
abstractmethod:
A decorator indicating abstract methods. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden. The abstractmethod() only affects subclasses derived using regular inheritance; “virtual subclasses” registered with the ABC’s register() method are not affected.
abstractproperty:
A subclass of the built-in property(), indicating an abstract property.
Note: In python, the abstract methods can have implementation. This implementation can be called via the super() mechanism from the class that overrides it. The abstract property declared above is the read only. To define read-write abstract property, refer python official documentation.
No comments:
Post a Comment