生成器:

yield的功能:

    1:与return类似,都可以返回值,不一样的地方,return可以返回多次值

    2:为函数封装好了__iter__和__next__方法,把函数的执行结果做成迭代器

   3:遵循迭代器的取值方式obj.__next__(),触发的函数的执行,函数暂停

 

反射:

已字符串的形式获取对象的属性
class Teacher:
    school='oldboy'
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def teach(self):
        print('%s teach' %self.name)
t=Teacher('egon',18)
print(hasattr(t,'name'))
print(getattr(t,'name'))
setattr(t,'sex','male')
print(getattr(t,'sex'))
View Code

 应用:

class Cmd:
    def __init__(self,name):
        self.name=name
    def run(self):
        while True:
            cmd=input('>>: ').strip()
            if not cmd:continue
            if hasattr(self,cmd):
                func=getattr(self,cmd)
                func()
            else:
                print('not valid func')
    def ls(self):
        print('ls function')

    def pwd(self):
        print('pwd function')

    def cat(self):
        print('cat function')

c=Cmd('egon')
c.run()
View Code

 

posted on 2018-07-10 18:39  lxltxdy  阅读(71)  评论(0)    收藏  举报