Check if NotImplementedError function is called before it is called in Python

I have the following simplified diagram:

class NetworkAnalyzer(object):
    def __init__(self):
       print('is _score_funct implemented?')

    @staticmethod
    def _score_funct(network):
        raise NotImplementedError

class LS(NetworkAnalyzer):
    @staticmethod
    def _score_funct(network):
        return network

and I'm looking for what I should use instead print('is _score_funct implemented?')to find out if a subclass is already implemented _score_funct(network)or not.

Note. If there is a more pythonic / regular way of structuring code, I would also like to mention its mention. The reason I defined it this way: some NetworkAnalyzer subclasses have _score_funct in their definition, and those that don't have it will have different variable initialization, although they will have the same structure

+4
source share
2 answers

, , :

import abc

class NetworkAnalyzerInterface(abc.ABC):
    @staticmethod
    @abc.abstractmethod
    def _score_funct(network):
        pass

class NetworkAnalyzer(NetworkAnalyzerInterface):
    def __init__(self):
        pass

class LS(NetworkAnalyzer):
    @staticmethod
    def _score_funct(network):
        return network

class Bad(NetworkAnalyzer):
    pass

ls = LS()   # Ok
b = Bad()   # raises TypeError: Can't instantiate abstract class Bad with abstract methods _score_funct
+3

/, , ( , / ):

, , getattr , ( ):

class NetworkAnalyzer(object):
    def __init__(self):
        funcname = "_score_funct"
        d = getattr(self,funcname)
        print(d.__qualname__.partition(".")[0] == self.__class__.__name__)

_score_funct LS, d.__qualname__ - LS._score_funct, NetworkAnalyzer._score_funct.

, LS. :

d.__qualname__.partition(".")[0] != "NetworkAnalyzer"

, - , NotImplementedError, ... ( )

+1

Source: https://habr.com/ru/post/1696284/


All Articles