I'm wondering if in python (3) an abstract class can have concrete methods.
Although this seems to work I'm not sure this is the proper way to do this in python:
from abc import ABCMeta, abstractclassmethod, abstractmethod
class MyBaseClass:
__metaclass__ = ABCMeta
@property
@abstractmethod
def foo_prop(self):
"""Define me"""
pass
@abstractclassmethod
def get_something(cls, param1, param2, param3):
"""This is a class method, override it with @classmethod """
pass
@classmethod
def get(cls, param1, param2):
"""Concrete method calling an abstract class method and an abstract property"""
if param1 < cls.foo_prop:
raise Exception()
param3 = param1 + 42
item = cls.get_something(param1, param2, param3)
return item
class MyConcreteClassA(MyBaseClass):
"""Implementation """
foo_prop = 99
@classmethod
def get_something(cls, param1, param2, param3):
return cls.foo_prop + param1 + param2 + param3
class MyConcreteClassB(MyBaseClass):
"""Implementation """
foo_prop = 255
@classmethod
def get_something(cls, param1, param2, param3):
return cls.foo_prop - param1 - param2 - param3
In the example the abstract class MyBaseClass
has:
- an abstract property
foo_prop
that will be defined in the subclasses- the only way I could find to declare this was to create an abstract "property method"
- an abstract class method
get_something
that will be implemented in the subclasses - a concrete method
get
that in turns uses the (not yet defined) abstract method and property mentioned above.
Questions:
Is there a better way to define an abstract property? Would it make more sense to define a concrete property in
MyBaseClass
set to None and just redefine it in the subclasses?Can I mix abstract and concrete methods in an abstract class as shown in the example?
If yes, does it always makes sense to declare the class abstract or can a concrete class have abstract methods (in this case it should never be instantiated directly anyway).
Thanks