还是看源代码:
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__的区别。