Python Abstract classes are more like JAVA Call the interface of , It is helpful in realizing polymorphic encapsulation :
This knowledge point , The example of skill tree interpretation is better , however , The definition of the concept is somewhat verbose , I made it simple .
Abstract class is a special class , Can only be inherited , Can't be instantiated ,
Subclasses of integrated abstract classes must implement abstract methods , Otherwise, an error will be reported :
import abc # utilize abc Modules implement abstract classes
class shuiguo(metaclass=abc.ABCMeta):
all_type='sg'
def name(self):
def func(self):
class Apple(shuiguo): # Subclass inherits abstract class , But it must be defined read and write Method
def name(self):
print(' I'm an apple ')
def func(self):
print(' delicious ')
class Pear(shuiguo): # Subclass inherits abstract class , But it must be defined read and write Method
def name(self):
print(' I'm a pear ')
def func(self):
print(' It's sweeter than apple ')
apple =Apple()
pear=Pear()
apple.name()
apple.func()
pear.name()
pear.func()
print(pear.all_type)
print(apple.all_type)
Output results :
delicious
I'm a pear
sg
sg
import abc # utilize abc Modules implement abstract classes
Source code
@abc.abstractmethod # Define abstract methods , There's no need to implement functions
def name(self):
pass
This is the standard way to write an abstract class ,@abc.abstractmethod【 Practice may omit 】, pass Is the key statement to write . If you don't write , Will report a mistake :
IndentationError: expected an indented block
Source code
class Apple(shuiguo): # Subclass inherits abstract class , But it must be defined read and write Method
def name(self):
print(‘ I'm an apple ’)
Apple Is a class that can be instantiated , Inherited the abstract class shuiguo, such shuiguo Methods of abstract classes name,func In the instantiated Apple Class has been implemented .
Source code :
apple =Apple()
pear=Pear()
apple.name()
apple.func()
pear.name()
pear.func()
Instantiate objects , And called the methods of the abstract class .
import abc # utilize abc Modules implement abstract classes
class shuiguo(metaclass=abc.ABCMeta):
all_type='sg'
def name(self):
pass
def func(self):
pass
class Apple(shuiguo): # Subclass inherits abstract class , But it must be defined read and write Method
class Pear(shuiguo): # Subclass inherits abstract class , But it must be defined read and write Method
def name(self):
print(' I'm a pear ')
apple =Apple()
pear=Pear()
apple.name()
apple.func()
pear.name()
pear.func()
print(pear.all_type)
print(apple.all_type)
【 case , The code modification removed the abstract class read,write Methods , A compilation error occurs 】
File “”, line 20
class Pear(shuiguo): # Subclass inherits abstract class , But it must be defined read and write Method
^
IndentationError: expected an indented block