Python abstract base class usage 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.
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 |
#! Coding = UTF-8
From abc import ABCMeta, abstractmethod, abstractproperty
Class Foo:
_ Metaclass _ = ABCMeta
@ Abstractmethod
# Use the class Foo (metaclass = ABCMeta) syntax in python3.0
Def spam (self, a, B ):
Pass
@ Abstractproperty
Def name (self ):
Pass
Class Bar (Foo ):
Def spam (self, a, B ):
Print a, B
Def name ():
Pass
B = 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.
?
|
1
2
3
4 |
Class Crok (object ):
Def spam (self, a, c ):
Print "gork. span"
Foo. register (Grok)
|
I hope this article will help you with Python programming.