反射

反射

  反射指的是通过 ”字符串“ 对对象/类的属性或方法进行操作。

  反射的方法有:

    hasattr:通过 ”字符串“ 判断对象/类的属性或方法是否存在

    getattr:通过 ”字符串“ 获取对象/类的属性值或方法

    setattr:通过 ”字符串“ 设置(修改/添加)对象/类的属性值

    delattr:通过 ”字符串“ 删除对象/类的属性或方法

 

  注意:反射的四个方法都是python内置

 

1、hasattr

  通过 ”字符串“ 判断对象/类的属性或方法是否存在

class Foo:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def func(self):
        pass

foo_obj = Foo(10, 20, 30)

# hasattr:通过字符串 "x"、"y"、"z" 判断对象中是否存在属性 print(hasattr(foo_obj, "x")) print(hasattr(foo_obj, "y")) print(hasattr(foo_obj, "z")) # hasattr:通过字符串 "func" 判断对象中是否存在该方法 print(hasattr(foo_obj, "func"))

  执行结果:

True
True
True
True

 

2、getattr

  通过 ”字符串“ 获取对象/类的属性值或方法

class Foo:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def func(self):
        pass

foo_obj = Foo(10, 20, 30)

# getattr:通过字符串 "x"、"y"、"z" 来获取对象属性 print(getattr(foo_obj, "x")) print(getattr(foo_obj, "y")) print(getattr(foo_obj, "z")) # getattr:通过字符串 "func" 来获取对象的绑定方法 print(getattr(foo_obj, "func")) # 若该属性不存在,则返回 "不存在,默认值" print(getattr(foo_obj, "a", "不存在,默认值"))

  执行结果:

10
20
30
<bound method Foo.func of <__main__.Foo object at 0x00000000021B6508>>
不存在,默认值

 

3、setattr

  通过 ”字符串“ 设置对象/类的属性值;若该属性不存在,即添加 ,若存在,即修改

class Foo:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def func(self):
        pass

foo_obj = Foo(10, 20, 30)


# setattr:通过字符串 "x" 设置(修改)对象的属性值
print(getattr(foo_obj, "x"))
setattr(foo_obj, "x", 100)
print(getattr(foo_obj, "x"))
# 若不存在该属性,即添加该属性
setattr(foo_obj, "a", 200)
print(getattr(foo_obj, "a"))

  执行结果:

10
100
200

 

4、delattr

  通过 ”字符串“ 删除对象/类的属性或方法

class Foo:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def func(self):
        pass

foo_obj = Foo(10, 20, 30)


# delattr:通过字符串 "x" 删除对象的属性或方法
print(hasattr(foo_obj, "x"))
delattr(foo_obj, "x")
print(hasattr(foo_obj, "x"))

  执行结果:

True
False

 

5、反射的应用场景

  场景:用于校验用户输入

class FileControl:
    def run(self):
        while True:
            # 让用户输入上传或下载功能的命令
            user_input = input('请输入上传(upload)或下载(download)功能, 输入"quit"退出>>> ').strip()
            # 通过用户的字符串,调用相应的方法
            if hasattr(self, user_input):
                func = getattr(self, user_input)    # func --> upload , func --> download
                func()
            elif user_input == "quit":
                break
            else:
                print("输入有误...")

    def upload(self):
        print("文件正在上传...")

    def download(self):
        print("文件正在下载...")


file_obj = FileControl()
file_obj.run()

  执行结果:

请输入上传(upload)或下载(download)功能, 输入"quit"退出>>> upload
文件正在上传...
请输入上传(upload)或下载(download)功能, 输入"quit"退出>>> download
文件正在下载...
请输入上传(upload)或下载(download)功能, 输入"quit"退出>>> quit
posted @ 2020-10-27 18:38  chchcharlie、  阅读(91)  评论(0编辑  收藏  举报