http://blog.csdn.net/ly21st http://ly21st.blog.chinaunix.net
分类: Python/Ruby
2011-10-03 09:13:51
+++++++++++++++++++++++++++++++++++++++++++++
构造方法:
+++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++
property函数
__metaclass__=type
class Rectangle:
def __init__(self):
self.hight=self.width=0
def getSize(self):
return self.width,self.hight
def setSize(self,size):
self.width,self.hight=size
size=property(getSize,setSize)
a=Rectangle()
a.width=10
a.hight=5
print a.size
a.size=100,150
print a.width
__metaclass__=type
class MyClass:
def smeth():
print 'this is a static method'
smeth=staticmethod(smeth)
def cmeth(cls):
print 'this is a class method',cls
cmeth=classmethod(cmeth)
print MyClass.smeth()
print MyClass.cmeth()
++++++++++++++++++++++++++++++++++++++
用装饰器对上述方法进行修改:
__metaclass__=type
class MyClass:
@staticmethod
def smeth():
print 'this is a smeth'
@classmethod
def cmeth(cls):
print 'this is a cmeth'
print MyClass.smeth()
print MyClass.cmeth()
得到的结果都如下所示:
this is a smeth
None
this is a cmeth
None
迭代器
特殊方法__iter__是迭代器规则的基础。
不仅可以对序列和字典进行迭代,也可以对其他的对象进行迭代:实现__iter__方法的对象。
使用list构造方法显式地将迭代器转化为列表
示例1:
示例2:
class Fibs:
def __init__(self):
self.a=0
self.b=1
def next(self):
self.a,self.b=self.b,self.a+self.b
if self.a > 50: raise StopIteration
return self.a
def __iter__(self):
return self
fibs=Fibs()
a=list(fibs)
print a
def flatten(netsted):
for sublist in netsted:
for a in sublist:
yield a
netsted=[[1,2],[3,4],[7],9]
a=list(flatten(netsted))
print a
+++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++
递归生成器:def fun(netsted):
try:
for sublist in netsted:
for element in fun(sublist):
yield element
except TypeError:
yield netsted
netsted=[[1,2],[3,5],[8,9],10]
a=list(fun(netsted))
print a
生成器在旧版本的Python中是不可用的,下面介绍的是如何使用普通函数模拟生成器。
+++++++++++++++++++++++++++++++++++++++++++++++++++=
def fun(netsted):
result=[]
try:
try:
netsted + ''
except TypeError:pass
else: raise TypeError
for sublist in netsted:
for element in fun(sublist):
result.append(element)
except TypeError:
result.append(netsted)
return result
netsted=[1,2,3,4,5]
a=fun(netsted)
print a
+++++++++++++++++++++++++++++++++++++++++++++++++