python面向对象之反射

面向对象之反射

含义

专业解释:指程序可以访问、检测和修改本身状态或者行为的一种能力。

大白话:其实就是通过字符串来操作对象的数据和功能。

反射的四个方法

  • hasattr(object, str):判断对象是否含有字符串对应的数据或者功能
  • getattr(object, str):根据字符串获取对应的变量名或者函数名
  • setattr(object, key, value):根据字符串给对象设置键值对(名称空间中的名字)
  • delattr(object, str):根据字符串删除对象对应的键值对(名称空间中的名字)

实际应用

class Student:
    school = '清华大学'
    def get(self):
        pass

hasattr(object, str):判断对象是否含有字符串对应的数据或者功能

obj = Student()
print(hasattr(obj, 'school'))  # 输出:True
print(hasattr(obj, 'get'))  # 输出:True
print(hasattr(obj, 'abc'))  # 输出:False

getattr(object, str):根据字符串获取对应的变量名或者函数名

obj = Student()
print(getattr(obj, 'school'))  # 输出:清华大学
print(getattr(obj, 'abc'))  # 报错,类中没有abc的名称

setattr(object, key, value):根据字符串给对象设置键值对(名称空间中的名字)

obj = Student()
setattr(obj, 'name', 'tom')
print(obj.__dict__)  # 输出:{'name': 'tom'}
print(obj.name)  # 输出:tom

delattr(object, str):根据字符串删除对象对应的键值对(名称空间中的名字)

obj = Student()
setattr(obj, 'name', 'tom')
print(obj.__dict__)  # 输出:{'name': 'tom'}
delattr(obj, 'name')
print(obj.__dict__)  # 输出:{}

image

反射的应用场景

以后只要在业务中看到关键字:对象、字符串(用户输入、自定义、指定),那么肯定用反射。

比如如果我想要调用对象中的某个数据或者功能,但是我只能获取那个数据或功能的名称的字符串形式,这个时候就需要用到反射了。

实际案例

实现一个根据用户输入的指令不同,执行的功能不同

class FtpServer:
    def serve_forever(self):
        while True:
            inp = input('input your cmd>>: ').strip()
            cmd, file = inp.split()
            if hasattr(self, cmd):  # 根据用户输入的cmd,判断对象self有无对应的方法属性
                func = getattr(self, cmd)  # 根据字符串cmd,获取对象self对应的方法属性
                func(file)

    def get(self, file):
        print('Downloading %s...' % file)

    def put(self, file):
        print('Uploading %s...' % file)


obj = FtpServer()
obj.serve_forever()

input

get a.py

output

Downloading a.py...

input

put a.py

output

Uploading a.py...

image

posted @ 2022-06-13 19:50  Yume_Minami  阅读(82)  评论(0编辑  收藏  举报