首页 > 代码库 > python之元编程(元类实例)

python之元编程(元类实例)

本实例是元类实例,功能是记录该的子类的类名,并以树状结构展示子类的类名。

RegisterClasses继承自type,提供的功能是在__init__接口,为类创建了childrens的集合,并类名保存到对应的父类元组的childrens的集合中。

同时对__str__打印方法和__iter__迭代方法进行了定义,其中:

__iter__方法返回类名的childrens集合,并对其中的元素进行输入。

而Sharp继承自RegisterClasses, 当 for s in Sharp: print s,则会调用继承来的__iter__方法。

class Round(Shape): pass
class Square(Shape): pass
class Triangular(Shape): pass
class Boxy(Shape): pass

上述操作中,Round,Square,Triangular,Boxy均初始化一个childrens的集合,
同时,均将自身的类名添加到Shape元类的childrens的集合里。

class Circle(Round): pass
class Ellipse(Round): pass

上述操作中,Circle,Ellipse均初始化一个childrens的集合,
同时,均将自身的类名添加到Round,Shape的childrens的集合里,

原因是:Round的父类是Shape,故Circle,Ellipse均有两个父类。

代码如下:
#!/usr/bin/env python
# encoding: utf-8
"""
@author:
@contract:
@file: homework5_1.py
@time: 2016/10/26 14:22
"""
class RegisterClasses(type):
def __init__(cls, name, bases, atts):
super(RegisterClasses, cls).__init__(name, bases, atts)

#创建一个集合,这样继承元类,都会有一个childrens的集合
cls.childrens = set()

#将把当前的子类保存到父类中去
for base in bases:
if hasattr(base, ‘childrens‘):
base.childrens.add(cls)

#classmethod, called on class object
def __iter__(cls):
return iter(cls.childrens)

def __str__(cls):
if len(cls.childrens) > 0:
return cls.__name__ + ": " + ", ".join([sc.__name__ for sc in cls])
else:
return cls.__name__

class Shape(object):
__metaclass__ = RegisterClasses

print "---------------------"
class Round(Shape): pass
class Square(Shape): pass
class Triangular(Shape): pass
class Boxy(Shape): pass
print Shape
print "---------------------"
class Circle(Round): pass
class Ellipse(Round): pass
print Shape
print "---------------------"
for s in Shape: #Iterator over subclasses (def __str__(cls):)
print s
print "---------------------"
for cls in Shape.childrens:
if len(cls.childrens) > 0:
print cls.__name__ + ": " + ", ".join([sc.__name__ for sc in cls])
else:
print cls.__name__

输出如下:

---------------------
Shape: Triangular, Boxy, Square, Round
---------------------
Shape: Triangular, Boxy, Square, Round
---------------------
Triangular
Boxy
Square
Round: Ellipse, Circle
---------------------
Triangular
Boxy
Square
Round: Ellipse, Circle




python之元编程(元类实例)