Determine if a Python class is an Abstract Base Class or Concrete

后端 未结 3 1437
无人及你
无人及你 2020-12-16 09:58

My Python application contains many abstract classes and implementations. For example:

import abc
import datetime
         


        
3条回答
  •  清酒与你
    2020-12-16 10:26

    import inspect
    print(inspect.isabstract(object))                  # False
    print(inspect.isabstract(MessageDisplay))          # True
    print(inspect.isabstract(FriendlyMessageDisplay))  # True
    print(inspect.isabstract(FriendlyMessagePrinter))  # False
    

    This checks that the internal flag TPFLAGS_IS_ABSTRACT is set in the class object, so it can't be fooled as easily as your implementation:

    class Fake:
        __abstractmethods__ = 'bluh'
    
    print(is_abstract(Fake), inspect.isabstract(Fake)) # True, False
    

提交回复
热议问题