0

Developing a metaclass that provides self-registration of subclasses (somewhat similar to this idea), I came across the following problem:

Given a class that may be either an abstract base class or an implementation of one, how do I distinguish which it is?

Emilia Bopp
  • 866
  • 10
  • 20
  • err, you don't distinguish the two : that's what abstraction is for. If not, your architecture should be reviewed. If you really want to make the separation, you can always use the **__class__** variable – lucasg Oct 11 '13 at 12:08
  • 1
    Define what makes a class abstract and check that condition. For example you might want to check that `SomeClass.method is not AbstractClass.method`, i.e. `SomeClass` has redefined the abstract method. – Bakuriu Oct 11 '13 at 12:15
  • Well, the point is, I want to register them for deserialization and only deserialize those classes that inherit my abstract base class. However, it does not make a lot of sense to deserialize something with an abstract base class as a type. Therefore, I wanted to skip the registration of the base class itself. – Emilia Bopp Oct 11 '13 at 12:15
  • @Bakuriu: this still depends on the particular abc you work with. Is there a more general way to do it? How does ABCMeta figure out, whether everything has been implemented? – Emilia Bopp Oct 11 '13 at 12:19
  • 1
    Pretty simple: it provides an `abstractmethod` decorator that you **must** apply to the methods that are abstract. Then when the metaclass is called at class construction it can check whether there are methods that are `abstractmethod`s. It does this adding an `__isabstractmethod__` attribute to the methods. If any method has that attribute set to `True` then the class is abstract, otherwise it can be instantiated. – Bakuriu Oct 11 '13 at 16:10
  • I see... I was not aware of the `__isabstractmethod__` attribute. That does answer my question. If it were an answer, I would accept it ;) – Emilia Bopp Oct 11 '13 at 16:28

0 Answers0