Python abstract base class usage instance analysis, python abstract instance analysis
This example describes the usage of the python abstract base class. Share it with you for your reference. The details are as follows:
To define an abstract class, you must use the abc module. This module defines an element class (ABCMeata), and the decorator @ abstractmethod, @ abstractproperty
If you want to instantiate a subclass that inherits Foo, The subclass must implement all the abstract methods of Foo (same as java); otherwise, an error is returned for instantiation.
Abstract classes cannot be instantiated directly.
#! Coding = utf-8from abc import ABCMeta, abstractmethod, abstractpropertyclass Foo: _ metaclass _ = ABCMeta @ abstractmethod # Use class Foo (metaclass = ABCMeta) syntax def spam (self, a, B): pass @ abstractproperty def name (self): passclass Bar (Foo): def spam (self, a, B): print a, B def name (): passb = Bar () B. spam (1, 2)
Abstract base classes support registering existing classes to belong to this base class, using the register () method
Register a class with the abstract base class. For an instance in the registration Class, Class detection operations involving subsequent base classes such as (isinstance, issubclass) will return True. When registering a class with the abstract base class, it does not check whether the class implements any abstract methods or features. This registration process only affects the type check.
Class Crok (object): def spam (self, a, c): print "gork. span" Foo. register (Grok)
I hope this article will help you with Python programming.