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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值