Python 面向对象之反射

Python 面向对象之反射

【一】概念

  • 反射是指通过对象的属性名或者方法名获取对象的属性或调用方法的能力
  • 反射还指的是在程序额运行过程中可以动态获取对象的信息(属性和方法)

【二】四个内置函数

  • 又叫做反射函数

  • 万物皆对象(整数、字符串、函数、模块、类等等)

  • 万物皆对象(整数、字符串、函数、模块、类等等)

  • 万物皆对象(整数、字符串、函数、模块、类等等)

  • 这里提到的对象都是大概念的对象

【1】hassttr

(1)概念
  • hasattr(object, str)

  • 判断对象是否有相应属性或者方法

  • 第一个参数是对象,第二个参数属性或者方法的字符串

  • 返回值为bool值,有则True,无则False

  • 注意:类无法找到实例属性

(2)代码
class A:
    name = "bruce"

    def __init__(self):
        self.age = 18

    def eat(self):
        print(f"{self.name}eating")

# 查看类是否具有相应属性和方法
print(hasattr(A, "name"))  # True
print(hasattr(A, "age"))  # False
print(hasattr(A, "eat"))  # True

# 查看对象是否具有相应属性和方法
a = A()
print(hasattr(a, "name"))  # True
print(hasattr(a, "age"))  # True
print(hasattr(a, "eat"))  # True

【3】getattr

(1)概念
  • getattr(object, name[, default])

  • 获取对象的属性或者方法

  • 第一个参数是对象,第二个参数属性或者方法的字符串,第三个参数是找不到返回的默认值

  • 返回值为属性或者方法或默认值,找不到也没有默认值会报错

(2)代码
class A:
    name = "bruce"
    def __init__(self):
        self.age = 18
    def eat(self):
        print(f"{self.name} is eating")
        
a = A()
print(getattr(a, "name"))  # bruce
print(getattr(a, "age"))  # bruce
res = getattr(a, "eat")  # # <bound method A.eat of <__main__.A object at 0x000>>
res()  # bruce is eating
# getattr(a, "nname") # 报错
print(getattr(a, "nname", "找不到"))  # 找不到

【3】setattr

(1)概念
  • setattr(object, str)

  • 设置对象的属性或者方法

  • 第一个参数是对象,第二个参数是属性的字符串或者方法地址

  • 已有就修改,没有就添加

  • 注意:给实例添加的方法是属性

(2)代码
class A:
    name = "bruce"
    def __init__(self):
        self.age = 18
    def eat(self):
        print(f"{self.name} is eating")

a = A()
setattr(a, "name", "lily")
print(getattr(a, "name"))  # lily
setattr(a, "age", 20)
print(getattr(a, "age"))  # 20


def func(self):
    print("类外的函数1")
# 给实例添加的一个属性,他是方法
setattr(a, "func", func)
print(a.__dict__)  # {'age': 20, 'name': 'lily', 'func': <function func at 0x000>}
a.func(a)  # 类外的函数1


def func(self):
    print("类外的函数2")
# 给类添加了一个方法
setattr(A, "func", func)
A.func(a)  # 类外的函数2
a.func(a)  # 类外的函数1

【4】delattr

(1)概念
  • delattr(object, str)

  • 删除对象的属性或者方法

  • 第一个参数是对象,第二个参数是属性或者方法的字符串

  • 没有返回值,删除没有的会报错

  • 注意通过实例无法删除类属性或者方法

(2)代码
class A:
    name = "bruce"
    def __init__(self):
        self.age = 18
    def eat(self):
        print(f"{self.name} is eating")


# 对属性操作
a = A()
# delattr(a, "name") # 无法删除
delattr(a, "age")
print(getattr(a, "age", "找不到"))  # 找不到
delattr(A, "name")
print(getattr(A, "name", "找不到"))  # 找不到

# 对方法操作
a = A()
# delattr(a, "eat") # 无法删除
print(getattr(A, "eat", "找不到"))  # 找不到

【三】应用

【1】反射当前模块成员

  • 用于查看当前模块下的
import sys

class A:
    pass
class B(A):
    pass
def func():
    pass

module_member = sys.modules[__name__]
print(module_member)
# <module '__main__' from 'D:\\Python\\PythonProjects\\My_projects\\tets_tempory\\main.py'>
print(hasattr(module_member, "B"))  # True
print(hasattr(module_member, "func"))  # True

【2】动态导入模块

  • 通过importlib模块导入所需要的模块,通过ImportError异常判断模块是否能导入
  • 通过getattr反射获取模块的方法,通过AttributeError异常判断该模块是否具有这个方法
import importlib

module_name = input("module name:>>>")
method_name = input("method name:>>>")
try:
    module = importlib.import_module(module_name)
    method = getattr(module, method_name)
    method()
except ImportError:
    print("module not found")
except AttributeError:
    print("method not found")

【3】动态创建对象

class FirePeaShooter:
    def introduce(self):
        print("I`m FirePeaShooter")

class IcePeaShooter:
    def introduce(self):
        print("T`m IcePeaShooter")

type = input("input type (fire or ice):>>>")
global_class = globals()

if "fire" in type:
    class_type = "FirePeaShooter"
    obj = global_class[class_type]()
    obj.introduce()
elif "ice" in type:
    class_type = "IcePeaShooter"
    obj = global_class[class_type]()
    obj.introduce()
else:
    print("wrong")

【四】总结

请添加图片描述

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值