第九章-魔法模块、属性和迭代器——python基础教程(第二版)笔记

9.2构造方法

#9.2.1重写一般方法和特殊方法
class A:
    def hello(Self):
        print "A"
class B(A):
    pass
a=A()
b=B()
a.hello() #结果   A
b.hello() #结果   A
class B(A):#简单重写
    def hello(self):
        print "B"
b=B()
b.hello() #结果 B
#特殊方法
class bird:
        def __init__(self):
                self.hungry = True
                self.thirsty = True
                self.insky = False
        def eat(self):
                if (self.hungry == True):
                        print "I am eating! Aaaaaaaaaaah~"
                        self.hungry = False
                else:
                        print "I am full! I don not want to eat anything!"
        def drink(self):
                if (self.thirsty == True):
                        print "I am drinking water. Gu lu, Gu lu, Gu lu~"
                        self.thirsty = False
                else:
                        print "Too much water! Now I do not need water."
        def takeoff(self):
                if (self.hungry == True):
                        print "I am too hungry to fly. Please run bird.eat()"
                elif (self.thirsty == True):
                        print "I am too thirsty to fly. Please run bird.drink()"
                else:
                        if(self.insky == False):
                                print "I am ready to fly! Takeoff now! Pu pu pu pu ~"
                                self.insky = True
                        else:
                                print "I am already in the sky! Wow!"
        def landing(self):
                if (self.insky == True):
                        print "I am tired. Now I am going to takeoff."
                        self.insky = False
                else:
                        print "I have already on the land."
        def sing(self):
                print "Squawk! Squawk! Squawk!"
b = bird()
b.takeoff()#结果 I am too hungry to fly. Please run bird.eat()
b.eat()
class Bird:
    def __init__(self):
        self.hungry=True
    def eat(self):
        if self.hungry:
            print "Aaaah"
            self.hungry=False
        else:
            print "No"
c=Bird()
c.eat() #结果 Aaaah
c.eat() #结果 No
class SongBird(Bird):
    def __init__(self):
        self.sound="Squawk"
    def sing(self):
        print self.sound
sc=SongBird()
sc.sing() #结果 Squawk

#9.2.2调用未绑定的超类构造方法
class SongBird(Bird):
    def __init__(self):
        Bird.__init__(self)
        self.sound="Squawk"
    def sing(self):
        print self.sound
sc=SongBird()
sc.sing() #结果 Squawk
sc.eat()#结果Aaaah
sc.eat()#结果 No

#9.2.3使用super函数
__metaclass__=type  #super只在新式类中起作用
class Bird:
    def __init__(self):
        self.hungry=True
    def eat(self):
        if self.hungry:
            print "Aaaah"
            self.hungry=False
        else:
            print "No"
class SongBird(Bird):
    def __init__(self):
        super(SongBird,self).__init__()
        self.sound="Squawk"
    def sing(self):
        print self.sound
sc=SongBird()
sc.sing() #结果 Squawk
sc.eat()#结果Aaaah
sc.eat()#结果 No

9.5属性

#9.5.1prooperty函数
__metaclass__=type
class Rectangle:
    def __init__(self):
        self.width=0
        self.height=0
    def setSize(self,size):
        self.width,self.height=size 
    def getSize(self):
        return self.width,self.height
    size=property(getSize,setSize)
r=Rectangle()
r.width=10
r.height=5
print r.size  #结果(10, 5)
r.size=150,100
print r.width  #结果150

#9.5.2静态方法和类成员方法
__metaclass__=type
class Myclass:
    def smeth():
        print "static method"
    smeth=staticmethod(smeth)
    def cmeth(cls):
        print "class method of",cls 
    cmeth=classmethod(cmeth)
Myclass.smeth()  #结果 static method

__metaclass__=type
class Myclass:
    @ staticmethod
    def smeth():
        print "static method"
    @classmethod
    def cmeth(cls):
        print "class method of",cls 
Myclass.smeth()  #结果 static method
Myclass.cmeth() #结果 class method of <class '__main__.Myclass'>

#9.5.3 __getattr__,__setatter__,etc

9.6迭代器

#9.6.1迭代器规则
class Fibs:
    f __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 #结果1597
        break

#9.6.2从迭代器得到序列
class Testlterator:
    value=0
    def next(self):
        self.value+=1
        if self.value>10:raise StopIteration
        return self.value
    def __iter__(self):
        return self
ti=Testlterator()
print list(ti)  #结果[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

9.7生成器

#9.7.1创建生成器
def flatten(nested):
    for sublist in nested:
        for element in sublist:
            yield element
nested=[[1,2],[3,4],[5]]
for num in flatten(nested):
    print num
'''
1
2
3
4
5
'''
print list(flatten(nested))  #结果[1, 2, 3, 4, 5]

#9.7.2递归生成器
def flatten(nested):
    try:       
        for sublist in nested:
            for element in flatten(sublist):
                yield element
    except TypeError:
        yield nested
print list(flatten([[1,2],[3,4],[5]]))  #结果[1, 2, 3, 4, 5]

9.8八皇后问题

#定义冲突
def conflict(state,nextX):
    nextY=len(state)
    for i in range(nextY):
        if abs(state[i]-nextX) in (0,nextY-i):
            return True
    return False
#放置最后一个皇后
def queens(num=8,state=()):
    for pos in range(num):
        if not conflict(state,pos):
            if len(state)==num-1:
                yield (pos,)
#需要递归的情况    
            else:
                for result in queens(num,state+(pos,)):
                    yield(pos,)+result
#print list(queens(4,(1,3,0))) #测试queen和conflict  输出2
print list(queens(3)) #结果  []
print list(queens(4)) #结果 [(1, 3, 0, 2), (2, 0, 3, 1)]
def prettyprint(solution):
    def line(pos,length=len(solution)):
        return "+"*(pos)+"X"+"+"*(length-pos-1)
    for pos in solution:
        print line(pos)
import random
prettyprint(random.choice(list(queens(8))))
'''
+++X++++
X+++++++
++++X+++
+++++++X
+X++++++
++++++X+
++X+++++
+++++X++
'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值