python反射

一、简单列举几个方法

可以点到函数类中查看方法

  1. hasattr() 函数用于检查对象是否具有指定的属性或方法

  2. getattr() 根据字符串获取对应的变量名或者函数名

  3. setattr() 根据字符串给对象设置数据 (名称空间的名字)

  4. delattr() 根据字符串删除对象对应的数据 (名称空间中的名字)

  5. dir():获取对象的所有属性和方法的列表。可以使用dir()函数来获取对象的所有属性和方法的列表。

  6. type():获取对象的类型。可以使用type()函数来获取对象的类型信息。

  7. inspect模块:该模块提供了更加高级的反射功能,可以用于获取函数和类的参数列表、注解、源代码等信息。

  8. callable() 是一个内置函数,用于检查对象是否可调用。

  9. __annotations__用于存储函数的注解信息

二、例子

1、上述文中的例子

1、hasattr() 判断对象是否含有字符串对应的数据或者功能

class Cat:
    name='123'
    def printagename(self):
        print('111')

print(hasattr(Cat(), "name"))
print(hasattr(Cat(), "printagename"))
print(hasattr(Cat(), "123"))

2、getattr() 根据字符串获取对应的变量名或者函数名

class Cat:
    name = '123'
    def printagename(self):
        print('111')
    def zzzz(self, value, aaa):  # 加上参数 value
    	print(value + aaa)

# 1.获取类中的值
print(getattr(Cat,'name'))

# 2.获取类中的方法
print(getattr(Cat,'printagename'))


# 3.调用函数
ccc = Cat()
getattr(Cat,'printagename')(ccc) # 这个写法类似于 1、ccc = Cat()   2、method = getattr(Cat,'printagename')   3、method(ccc)

# 4. 如果有参数的函数如何调取

aaa = Cat()
method = getattr(Cat,'zzzz')
method(aaa, "vvv","ccc")


# 5.获取对象中的属性值
print(getattr(ccc,'name'))

运行结果如下
在这里插入图片描述

3、 setattr() 根据字符串给对象设置数据 (名称空间的名字)

class Cat():
    name='123'
    def printagename(self):
        print('111')
# 1.获取类中的值
print(getattr(Cat,'name'))
#2.通过反射修改
setattr(Cat,'name','addddd')
#3.获取修改后结果
print(getattr(Cat,'name'))
  1. delattr() 根据字符串删除对象对应的数据 (名称空间中的名字)
class Cat():
    name='123'
    def printagename(self):
        print('111')
# 1.获取类中的值
print(getattr(Cat,'name'))
#2.通过反射删除
delattr(Cat,'name')
#3.获取修改后结果
print(getattr(Cat,'name'))

  1. dir():获取对象的所有属性和方法的列表。可以使用dir()函数来获取对象的所有属性和方法的列表。
class MyClass:
    def __init__(self):
        self.my_attribute = 'Hello, World!'

    def my_method(self):
        print(self.my_attribute)


# 使用 dir() 获取类的方法列表
print(dir(MyClass))


  1. type():获取对象的类型。可以使用type()函数来获取对象的类型信息。
class MyClass:
    def __init__(self):
        self.my_attribute = 'Hello, World!'

    def my_method(self):
        print(self.my_attribute)
# 使用 dir() 获取类的方法列表
print(type(MyClass))

创建对象

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

my_class = type("MyClass", (), {"x": 1, "y": 2})
my_object = my_class()
print(my_object.x, my_object.y)  # 输出 1 2
  1. inspect模块:该模块提供了更加高级的反射功能,可以用于获取函数和类的参数列表、注解、源代码等信息。
import inspect

def greet(name: str, age: int) -> None:
    print(f"Hello, {name}! You are {age} years old.")

# 获取函数的签名信息
signature = inspect.signature(greet)
print(signature)  # 输出函数的签名信息

# 获取函数参数信息
for param_name, param in signature.parameters.items():
    print(f"Parameter: {param_name}, Type: {param.annotation}, Default: {param.default}")

# 判断对象是否为函数
print(inspect.isfunction(greet))  # 输出: True

8、callable() 是一个内置函数,用于检查对象是否可调用。

class MyClass:
    def __call__(self):
        print("Calling MyClass")

def my_function():
    print("Calling my_function")

obj = MyClass()

print(callable(my_function))  # 输出: True,函数是可调用的
print(callable(obj))           # 输出: True,具有 __call__() 方法的对象是可调用的
print(callable(10))            # 输出: False,整数是不可调用的

  1. __annotations__用于存储函数的注解信息

在这里插入图片描述


def greet(name: str, age: int) -> None:
    print(f"Hello, {name}. You are {age} years old.")
    
greet.__annotations__["name"] = 132

print(greet.__annotations__)

在这里插入图片描述

三、查看链接实用场景

主要查看他创建对象的方式,以及实用场景(策略者模式)
链接

  • 22
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张航柯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值