我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用abc.abstractmethod()。
def setUpClass(cls): FinalABCMeta = final_meta_factory(ABCMeta) class ABCWithFinal(with_metaclass(FinalABCMeta, object)): a = final('ABCWithFinal: a') b = 'ABCWithFinal: b' @final def f(self): return 'ABCWithFinal: f' def g(self): return 'ABCWithFinal: g' @abstractmethod def h(self): raise NotImplementedError('h') cls.class_ = ABCWithFinal
def _find_abs_path( self, skt_path: str, origin_path: Optional[str]=None) -> str: # pragma: no cover """ This is an :func:`abc.abstractmethod`. Override this method to customize sketch discovery. Solve the absolute path(starting with :code:`/`) of the sketch from the skt_path based on the origin_path(if applicable). .. important:: If no matched file is found, it should raise a :class:`.SketchNotFoundError`. """ raise NotImplementedError
def setUpClass(cls): FinalABCMeta = compose_types(FinalMeta, ABCMeta) class ABCWithFinal(with_metaclass(FinalABCMeta, object)): a = final('ABCWithFinal: a') b = 'ABCWithFinal: b' @final def f(self): return 'ABCWithFinal: f' def g(self): return 'ABCWithFinal: g' @abstractmethod def h(self): raise NotImplementedError('h') cls.class_ = ABCWithFinal
def validate(self, level='max'): _check_validation_level(level) if not self.path.is_file(): raise ValidationError("%s is not a file." % self.path) if hasattr(self, '_validate_'): try: self._validate_(level) except ValidationError as e: raise ValidationError( "%s is not a(n) %s file:\n\n%s" % (self.path, self.__class__.__name__, str(e)) ) from e # TODO: remove this branch elif hasattr(self, 'sniff'): if not self.sniff(): raise ValidationError("%s is not a(n) %s file" % (self.path, self.__class__.__name__)) # TODO: define an abc.abstractmethod for `validate` when sniff is # removed instead of this else: raise NotImplementedError("%r does not implement validate." % type(self))
def test_cache_leak(self): # See issue #2521. class A(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def f(self): pass class C(A): def f(self): A.f(self) r = weakref.ref(C) # Trigger cache. C().f() del C test_support.gc_collect() self.assertEqual(r(), None)
def test_abstractproperty_basics(self): @property @abc.abstractmethod def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc.ABCMeta): @property @abc.abstractmethod def foo(self): return 3 self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertEqual(D().foo, 3)
def test_abstractclassmethod_basics(self): @classmethod @abc.abstractmethod def foo(cls): pass self.assertTrue(foo.__isabstractmethod__) @classmethod def bar(cls): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc.ABCMeta): @classmethod @abc.abstractmethod def foo(cls): return cls.__name__ self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D') self.assertEqual(D().foo(), 'D')
def test_abstractstaticmethod_basics(self): @staticmethod @abc.abstractmethod def foo(): pass self.assertTrue(foo.__isabstractmethod__) @staticmethod def bar(): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc.ABCMeta): @staticmethod @abc.abstractmethod def foo(): return 3 self.assertRaises(TypeError, C) class D(C): @staticmethod def foo(): return 4 self.assertEqual(D.foo(), 4) self.assertEqual(D().foo(), 4)
def __init__(self, logger, page_url, *args, **kwargs): self.json_data = None self.media_urls = None self.file_name = '' self.logger = logger self.page_url = page_url self.args = args self.kwargs = kwargs # @abc.abstractmethod # def get_params(self): # pass # # @abc.abstractmethod # def get_video_info(self, response): # pass
def __new__(cls, **kwargs): """Patch for abstractmethod-like enforcement in io.IOBase grandchildren.""" if ( not (hasattr(cls, '_read_bytes') and callable(cls._read_bytes)) or not (hasattr(cls, '_prep_message') and callable(cls._read_bytes)) or not hasattr(cls, '_config_class') ): raise TypeError("Can't instantiate abstract class {}".format(cls.__name__)) instance = super(_EncryptionStream, cls).__new__(cls) config = kwargs.pop('config', None) if not isinstance(config, instance._config_class): # pylint: disable=protected-access config = instance._config_class(**kwargs) # pylint: disable=protected-access instance.config = config instance.bytes_read = 0 instance.output_buffer = b'' instance._message_prepped = False # pylint: disable=protected-access instance.source_stream = instance.config.source instance._stream_length = instance.config.source_length # pylint: disable=protected-access return instance
def test_cannot_instantiate_subclass(self): """ Tests that you cannot create an instance of a subclass that does not implement the abstractmethod h. """ class AbstractSubClass(self.class_): pass with self.assertRaises(TypeError): AbstractSubClass()
def test_abstract_subclasses(self): AbstractSubclass = ABCMeta( 'AbstractSubclass', (greenlet,), {'run': abstractmethod(lambda self: None)}) class BadSubclass(AbstractSubclass): pass class GoodSubclass(AbstractSubclass): def run(self): pass GoodSubclass() # should not raise self.assertRaises(TypeError, BadSubclass)
def _uabstractmethod(f): @_wraps(f) def func(*args): raise NotImplementedError() return _abstractmethod(func)
def _load_sketch_content( self, skt_path: str) -> Union[str, bytes]: # pragma: no cover """ This is an :func:`abc.abstractmethod`. Override this method to customize sketch loading. Load the sketch content as string or bytestring. .. important:: If no matched file is found, it should raise a :class:`.SketchNotFoundError`. """ raise NotImplementedError
def __init__(self, protocol): self.protocol = protocol # The following two methods are the minimum required to be implemented by subclasses, but the name and number of # kwargs differs between services. Therefore, we cannot make these methods abstract. # @abc.abstractmethod # def call(self, **kwargs): # raise NotImplementedError() # @abc.abstractmethod # def get_payload(self, **kwargs): # raise NotImplementedError()
def GetResourceType(self, resourceDefinition): return # @abc.abstractmethod # def GetResourceSupportedOperations(self, resourceDefinition): # return #
def DefineWithSession(self, session, objectDefinitionSettings, resourceDefinitionSettingsCollection): return # @abc.abstractmethod # def CreateObjectDefinitionIterator(self, session): # return # # @abc.abstractmethod # def GetNextObjectDefinitionFromIterator(self, iterator): # return
def clear_auth(self): """Clear access cache Can be called to clear the access cache so that next request will fetch a new token and base_url. """ self.cache = None self.credentials.reset() #@abc.abstractmethod #ef is_expired(self, auth_data): # return
def test_abstractmethod_basics(self): @abc.abstractmethod def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(hasattr(bar, "__isabstractmethod__"))
def test_abstractmethod_integration(self): for abstractthing in [abc.abstractmethod, abc.abstractproperty, abc.abstractclassmethod, abc.abstractstaticmethod]: class C(metaclass=abc.ABCMeta): @abstractthing def foo(self): pass # abstract def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, C) # because foo is abstract self.assertTrue(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, D) # because foo is still abstract self.assertTrue(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too self.assertFalse(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, {"bar"}) self.assertRaises(TypeError, F) # because bar is abstract now self.assertTrue(isabstract(F))
def test_metaclass_abc(self): # Metaclasses can be ABCs, too. class A(metaclass=abc.ABCMeta): @abc.abstractmethod def x(self): pass self.assertEqual(A.__abstractmethods__, {"x"}) class meta(type, A): def x(self): return 1 class C(metaclass=meta): pass
def test_abstractmethod_integration(self): for abstractthing in [abc.abstractmethod, abc.abstractproperty]: class C: __metaclass__ = abc.ABCMeta @abstractthing def foo(self): pass # abstract def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, set(["foo"])) self.assertRaises(TypeError, C) # because foo is abstract self.assertTrue(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, set(["foo"])) self.assertRaises(TypeError, D) # because foo is still abstract self.assertTrue(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too self.assertFalse(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, set(["bar"])) self.assertRaises(TypeError, F) # because bar is abstract now self.assertTrue(isabstract(F))
def abstractmethod(func): return func # def abstractproperty(): # return None
def _set_info(self): '''save useful info about table/datasource''' pass #@abc.abstractmethod #def get_connection(self): # '''get con[nection] for database handles''' # pass
def abstractmethod(self): return self ### ONE-TRICK PONIES ### #class Iterable(metaclass=ABCMeta):
def test_descriptors_with_abstractmethod(self): class C(metaclass=abc.ABCMeta): @property @abc.abstractmethod def foo(self): return 3 @foo.setter @abc.abstractmethod def foo(self, val): pass self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertRaises(TypeError, D) class E(D): @D.foo.setter def foo(self, val): pass self.assertEqual(E().foo, 3) # check that the property's __isabstractmethod__ descriptor does the # right thing when presented with a value that fails truth testing: class NotBool(object): def __nonzero__(self): raise ValueError() __len__ = __nonzero__ with self.assertRaises(ValueError): class F(C): def bar(self): pass bar.__isabstractmethod__ = NotBool() foo = property(bar)
def test_customdescriptors_with_abstractmethod(self): class Descriptor: def __init__(self, fget, fset=None): self._fget = fget self._fset = fset def getter(self, callable): return Descriptor(callable, self._fget) def setter(self, callable): return Descriptor(self._fget, callable) @property def __isabstractmethod__(self): return (getattr(self._fget, '__isabstractmethod__', False) or getattr(self._fset, '__isabstractmethod__', False)) class C(metaclass=abc.ABCMeta): @Descriptor @abc.abstractmethod def foo(self): return 3 @foo.setter @abc.abstractmethod def foo(self, val): pass self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertRaises(TypeError, D) class E(D): @D.foo.setter def foo(self, val): pass self.assertFalse(E.foo.__isabstractmethod__)
def __iter__(self): yield('Feed', dict(self._stree.snode_root)) # @abc.abstractmethod # def create(self, **kwargs): # """Create a new tree # # """
def test_ABC_helper(self): # create an ABC using the helper class and perform basic checks class C(abc.ABC): @classmethod @abc.abstractmethod def foo(cls): return cls.__name__ self.assertEqual(type(C), abc.ABCMeta) self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D')
def test_descriptors_with_abstractmethod(self): class C(metaclass=abc.ABCMeta): @property @abc.abstractmethod def foo(self): return 3 @foo.setter @abc.abstractmethod def foo(self, val): pass self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertRaises(TypeError, D) class E(D): @D.foo.setter def foo(self, val): pass self.assertEqual(E().foo, 3) # check that the property's __isabstractmethod__ descriptor does the # right thing when presented with a value that fails truth testing: class NotBool(object): def __bool__(self): raise ValueError() __len__ = __bool__ with self.assertRaises(ValueError): class F(C): def bar(self): pass bar.__isabstractmethod__ = NotBool() foo = property(bar)