问题描述
BoardMeta是自定义元类,使用这个自定义元类创建了Board类,程序20行Board类不是已经创建过了吗?
#!/usr/bin/env python
# encoding: utf-8
_board_classes = {}
class BoardMeta(type): #元类
def __init__(cls, name, bases, dct):
super(BoardMeta, cls).__init__(name, bases, dct) #调用父类__init__()函数,父类是type(),用于创建类
if 'abstract' not in cls.__dict__: #属性中不含有abstract返回true
cls.abstract = False
if cls.abstract:
return
board_name = getattr(cls, 'name', name)
_board_classes[board_name] = cls
class Board(object):
abstract = True
def __init__(self):
pass
Board = BoardMeta('Board', Board.__bases__, dict(Board.__dict__)) #使用自定义元类BoardMeta动态创建类Board
class sitl(BoardMeta('Board', Board.__bases__, dict(Board.__dict__))):
pass
class linux(Board):
pass
class pxfplus(linux):
pass
def list_boards():
print(sorted(list(_board_classes.keys())))
list_boards()
以上代码运行输出[sitl, linux, pxfplus],程序是怎么运行的呢?