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

来源:互联网 发布:川一硅藻泥怎么样知乎 编辑:程序博客网 时间:2024/05/21 06:54

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.soundsb=Songbird()sb.sing()>>>Squawksb.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=classmethod(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',clsMyclass.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 selffibs=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 selfti=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 nestedlist(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 nestedlist(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 Falsedef 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 randomprettyprint(random.choice(list(quees(8))))   >>>...A.....A............A...A..........A.........AA...........A...
阅读全文
0 0
原创粉丝点击