“Can't instantiate abstract class … with abstract methods” on class that shouldn't have any abstract method

前端 未结 4 1776
遇见更好的自我
遇见更好的自我 2021-01-11 14:12

Take the following minimal example:

import abc

class FooClass(object):
  __metaclass__ = abc.ABCMeta

  @abc.abstractmethod
  def FooMethod(self):
    raise         


        
4条回答
  •  情话喂你
    2021-01-11 15:07

    Well, if you must do it this way, then you could just pass a dummy dict {'FooMethod':None} as the third argument to type. This allows derived_type to satisfy ABCMeta's requirement that all abstract methods be overridden. Later on you can supply the real FooMethod:

    def main():
      derived_type = type('Derived', (FooClass,), {'FooMethod':None})
      def BarOverride(self):
        print 'Hello, world!'
      setattr(derived_type, 'FooMethod', BarOverride)
      instance = derived_type()
    

提交回复
热议问题