HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python proper abstract class and subclassing with attributes and methods

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
abstractwithandsubclassingmethodsattributespythonproperclass

Problem

The goal of the code below is to have an abstract base class that defines simple methods and attributes for the subclasses. This is part of an application that provides the code base for others to develop their own subclasses such that all methods and attributes are well implemented in a way for the main application to use them. The application shall never create more than one object of each subclass, since they are supposed to implement everything correctly to be called upon. Ideally, instantiating objects of the subclasses would not even be necessary, but is needed as it is in order to check if the abstract methods are implemented.

However, Python seems to be different and awkward when it comes to classes in comparison with other programming languages (initialization, attributes, properties), and I am not very sure if the solution below is the most appropriate. It seems too much complicated to achieve the aforementioned purpose. In addition, another function (not in the code below) must be made to properly check (make sure that they are of a certain type) the attributes of the subclasses.

Any thoughts?

```
from abc import ABC, abstractmethod

class abstract_attribute(object):
"""taken from http://stackoverflow.com/questions/32536176/how-to-define-lazy-variable-in-python-which-will-raise-notimplementederror-for-a/32536493#32536493"""
def __get__(self, obj, type):
# Now we will iterate over the names on the class,
# and all its superclasses, and try to find the attribute
# name for this descriptor
# traverse the parents in the method resolution order
for cls in type.__mro__:
# for each cls thus, see what attributes they set
for name, value in cls.__dict__.items():
# we found ourselves here
if value is self:
# if the property gets accessed as Child.variable,
# obj will be done. For this case
# If acc

Solution

I don't see much of problems with using properties as abstract attributes e.g:

class Foo(abc.ABC):
    @property
    @abc.abstractmethod
    def bar(self):
        ...


However, if you still don't like it instead of going for your ninja stackoverflow way there is an easy way in python 3.6.

class Foo(abc.ABC):
    def __init_subclass__(cls, **kwargs):
        if not hasattr(cls, 'bar'):
            raise NotImplementedError('damn')
        return super().__init_subclass__(**kwargs)


As for one instance per class just look for python Singleton implementations.

Code Snippets

class Foo(abc.ABC):
    @property
    @abc.abstractmethod
    def bar(self):
        ...
class Foo(abc.ABC):
    def __init_subclass__(cls, **kwargs):
        if not hasattr(cls, 'bar'):
            raise NotImplementedError('damn')
        return super().__init_subclass__(**kwargs)

Context

StackExchange Code Review Q#153492, answer score: 6

Revisions (0)

No revisions yet.