您的位置:首页 > 编程语言 > Python开发

python零碎知识(6)--魔法方法、属性和迭代器

2017-09-17 11:21 671 查看
1.在类定义的开始加上:
__metaclass=type
,表明使用新式类

2.如果一个类的构造方法被重写,那么就需要调用调用超类的构造方法,否则对象不会被正常的初始化

即构造子类当构造方法被重写,子类不会有超类的属性

class Bird:
def __init__(self):
self.hungry=True
def eat(self):
if self.hungry:
print 'Aaah'
self.hungry=False
else:
print 'No,thanks'

class Songbird(Bird):
def __init__(self):
self.sound='Squawk'
def sing(self):
print self.sound

sb=Songbird()
sb.sing()
>>>Squawk
sb.eat()
>>>Traceback (most recent call last):

File "<ipython-input-7-05f67b3cf162>", line 1, in <module>
sb.eat()

File "<ipython-input-2-3cd50a94751c>", line 5, in eat
if self.hungry:

AttributeError: Songbird instance has no attribute 'hungry'


3.静态方法和类成员方法:

静态方法没有
self
参数,能够被类本身直接调用

类方法在是定义时需要
cls
(类似于
self
),类成员方法可以直接用类的具体对象调用,但
cls
参数是自动绑定到类的

class Myclass:
def smeth():
print 'This is a static method'
smeth=staticmethod(smeth)

def cmeth(cls):
print 'This is a class methodof',cls
cmeth=classmeth
4000
od(cemth)


4.装饰器:能够对任何可调用的对象进行包装,既能够用于方法,也能够用于函数,使用
@
操作符,在方法(或函数)的上方将装饰器列出,从而指定一个或者更多的装饰器(多个装饰器在应用时的顺序与指定顺序相反)

e,g:将3中的程序修改:

class Myclass(object):
@staticmethod
def smeth():
print 'This is a static method'
@classmethod
def cmeth(cls):
print 'This is a class method of',cls
Myclass.cmeth()
>>>This is a class method of <class '__main__.Myclass'>
Myclass.smeth()
>>>This is a static method


5.迭代器

1)特殊方法:
__iter__


class Fibs:
def __init__(self):
self.a=0
self.b=1
def next(self):
self.a,self.b=self.b,self.a+self.b
return self.a
def __iter__(self):
return self

fibs=Fibs()
for f in fibs:
if f>1000:
print f
break
>>>1549


2)从迭代器中得到序列

利用
list
构造方法显式的将迭代器转化为列表

class TestIterator:
value=0
def next(self):
self.value+=1
if self.value>10:
raise StopIteration
return self.value
def __iter__(self):
return self

ti=TestIterator()
list(ti)
>>>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


6.生成器

任何包含
yield
语句的函数称为生成器,每次产生多个值。每次产生一个值(使用
yield
语句),函数就会被冻结,即函数停在那点等待被重新唤起,函数被重新唤醒后就从停止的那点开始 执行

1)循环生成器

g=((i+2)**2 for i in range(2,27))
g.next()
>>>16


()
表示生成器推导式,
[]
表示列表生成式

2)循环生成器

def flatten(nested):
try:
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested

list(flatten([[1,2],3,4,[5,[6,7]],8]))
>>>[1, 2, 3, 4, 5, 6, 7, 8]


注:字符串不能用于迭代:

def flatten(nested):
try:
try:nested+''  #字符串型通过
except TypeError:pass
else:raise TypeError
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested

list(flatten([['a',2],'bcd',4,['hfz',[6,7]],8]))
>>>['a', 2, 'bcd', 4, 'hfz', 6, 7, 8]


测试
nest
是否是一个字符串,可使用
isinstance
,而测试
nest
的行为是不是像一个字符串,通过和字符串并接来接测。

7.八皇后问题

def conflict(state,nextX):#nextX表示水平位置,列
nextY=len(state)  #一行放置一样本
for i in range(nextY):
if abs(state[i]-nextX) in (0,nextY-i): #如果列相同或者在同一条对角线上,则会发生冲突
return True
return False

def quees(num=8,state=()):
for pos in range(num):
if not conflict(state,pos):
if len(state)==num-1:
yield (pos,)
else:
for result in quees(num,state+(pos,)):
yield (pos,)+result

def prettyprint(solution):
def line(pos,length=len(solution)):
return '.'*pos+'A'+'.'*(length-pos-1)
for pos in solution:
print line(pos)

import random
prettyprint(random.choice(list(quees(8))))
>>>...A....
.A......
......A.
..A.....
.....A..
.......A
A.......
....A...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: