面对对象之反射

TOC

一、什么是反射

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

反射的四个方法是python内置的!

1.1 hasattr

通过“字符串”判断对象/类的属性或方法是否存在,返回bool值。

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


foo_obj = Foo(10, 20)

print(hasattr(foo_obj, 'x'))  # 通过字符串x判断,因此此时X要用引号引起来
print(hasattr(foo_obj, 'z'))


>>>True
>>>False

1.2 getattr

通过“字符串”获取对象的属性或方法,若存在,返回获取的属性和方法,若不存在,会报错,当然也可以定义若不存在返回的值。

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


foo_obj = Foo(10, 20)

print(getattr(foo_obj, 'x'))
print(getattr(foo_obj, 'z'))


>>>10
>>>AttributeError: 'Foo' object has no attribute 'z'


# 若不存在可以定义返回的信息
print(getattr(foo_obj, 'z', '我是自定义返回的信息'))

>>>我是自定义返回的信息

1.3 setattr

通过“字符串”设置对象的属性和方法。

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


foo_obj = Foo(10, 20)
setattr(foo_obj, 'x', 30)  # 设置x的值,若存在就修改value,若不存在就新增属性

print(getattr(foo_obj, 'x'))

1.4 delattr

通过“字符串”删除对象的属性和方法。

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


foo_obj = Foo(10, 20)
delattr(foo_obj, 'x')  # 删掉x的属性

print(getattr(foo_obj, 'x', 'None'))  # 不存在返回None


>>> None

二、反射的应用

class FileControl:
    def run(self):
        while True:
            # 让用户输入上传或下载功能的命令
            user_input = input('请输入 上传(upload) 或 下载(download) 功能:').strip()
            if hasattr(self, user_input):
                func = getattr(self, user_input)
                func()
            else:
                print('输入有误!')

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

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


file_control = FileControl()
file_control.run()

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">





原文地址:https://www.cnblogs.com/cnhyk/p/11953526.html