day7_python之面向对象高级-反射

反射:通过字符串去找到真实的属性,然后去进行操作

 python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)

1、两种方法访问对象的属性

class Foo:
    x=1
    def __init__(self,name):
        self.name=name

    def f1(self):
        print('from f1')



f=Foo('egon')
print(f.__dict__)

方式一:访问那么对应的值

print(f.name)

方式二:

print(f.__dict__['name'])

2、反射

2.1、hasattr判断属性

class Foo:
    x = 1

    def __init__(self, name):
        self.name = name

    def f1(self):
        print('from f1')


f = Foo('egon')
print(hasattr(f, 'name'))  # f.name   判断f对象里有没有name这个属性,一定得是字符串形式的name
print(hasattr(f, 'f1'))  # f.f1
print(hasattr(f, 'x'))  # f.x

2.2、setattr 设置属性

class Foo:
    x = 1
    def __init__(self, name):
        self.name = name

    def f1(self):
        print('from f1')
f = Foo('egon')

setattr(f,'age',18)#f.age=18 给f设置一个age属性
print(f.age)

2.3、getattr 获取属性

class Foo:
    x = 1
    def __init__(self, name):
        self.name = name

    def f1(self):
        print('from f1')
f = Foo('egon')

print(getattr(f,'name'))#f.name
print(getattr(f,'abc',None))#f.abc
print(getattr(f,'name',None))#f.abc

func = getattr(f, 'f1')  # f.f1
print(func)
func()

2.4、delattr 删除属性

class Foo:
    x = 1
    def __init__(self, name):
        self.name = name

    def f1(self):
        print('from f1')
f = Foo('egon')
delattr(f,'name')# del f.name
print(f.__dict__)

3、反射的用法 

class Ftpserver:
    def __init__(self, host, port):
        self.host = host
        self.port = port

    def run(self):
        while True:
            cmd = input('>>: ').strip()
            if not cmd: continue
            if hasattr(self, cmd):  # 首先判断self(对象)里有没有用户输入的功能
                func = getattr(self, cmd)  # 用户输入的命令是个字符串,应该把字符串反射到正真的属性上
                func()

    def get(self):
        print('get func')

    def put(self):
        print('put func')


f = Ftpserver('192.168.1.2', 21)
f.run()

  

posted @ 2017-11-25 15:15  xiechao  阅读(179)  评论(0编辑  收藏  举报
levels of contents