python中的工程模式

还是看源代码:

from __future__ import generators
import random

class Shape(object):
    def factory(type):
        if type == "Circle":return Circle()
        if type == "Square":return Square()
        assert 1, "Bad shape creation"+type
    factory = staticmethod(factory)

class Circle(Shape):
    def draw(self):print "Circle.draw"
    def erase(self):print"Circle.erase"

class Square(Shape):
    def draw(self):print "Square.draw"
    def erase(self):print "Square.erase"
def shapeNameGen(n):
    types = Shape.__subclasses__()
    for i in range(n):
        yield random.choice(types).__name__
shapes =[Shape.factory(i) for i in shapeNameGen(7)]
print "*"*20
print shapes
print "*"*20
for shape in shapes:
    shape.draw()
    shape.erase()


注意其中的types = Shape.__subclasses__(),产生Shape子类的地址的一个list,打印出来就是[<class '__main__Circle'>,<class '__main__Square'>].

而randowm.choice(types),就是选择其中的一个类型。


另外注意其中的factory(),是表示Shape类型可以创造什么子类型。




class OnlyOne:
    class __OnlyOne:
        def __init__(self,arg):
            self.val = arg
        def __str__(self):
            return 'self'+self.val
    instance = None

    def __init__(self,arg):
        if not OnlyOne.instance:
            print "after onlyone.instance"
            OnlyOne.instance = OnlyOne.__OnlyOne(arg)
        else:
            OnlyOne.instance.val = arg

    def __getattr__(self,name):
        return getattr(self.instance,name)


x = OnlyOne('sausage')
print x
print OnlyOne.instance
y = OnlyOne("eggs")
print y



这个主要注意有__getattr__和无__getattr__的区别。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值