python abstractmethod with another baseclass breaks abstract functionality

后端 未结 2 1725
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 10:21

Consider the following code example

import abc
class ABCtest(abc.ABC):
    @abc.abstractmethod
    def foo(self):
             


        
2条回答
  •  庸人自扰
    2020-11-30 11:02

    I asked a similar question and based on user2357112 supports Monicas linked bug report, I came up with this workaround (based on the suggestion from Xiang Zhang):

    from abc import ABC, abstractmethod
    
    class Base(ABC):
        @abstractmethod
        def foo(self):
            pass
    
        @abstractmethod
        def bar(self):
            pass
    
        def __new__(cls, *args, **kwargs):
            abstractmethods = getattr(cls, '__abstractmethods__', None)
            if abstractmethods:
                msg = "Can't instantiate abstract class {name} with abstract method{suffix} {methods}"
                suffix = 's' if len(abstractmethods) > 1 else ''
                raise TypeError(msg.format(name=cls.__name__, suffix=suffix, methods=', '.join(abstractmethods)))
            return super().__new__(cls, *args, **kwargs)
    
    class Derived(Base, tuple):
        pass
    
    Derived()
    

    This raises TypeError: Can't instantiate abstract class Derived with abstract methods bar, foo, which is the original behaviour.

提交回复
热议问题