python 22 类反射

# python
# /usr/sbin/py/python
# -*-coding:utf8-*-
# pthon 反射
import abc
class Person(metaclass=abc.ABCMeta):
    "定义接口"

    @abc.abstractmethod
    def run(self):
        pass


class Student(Person):

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def run(self):
        print("%s is running" % self.name)


stu1 = Student("jake", 15)
stu1.run()
print(hasattr(stu1, "name"))  # hasattr方法判断一个实例中是否含有某个属性值
print(getattr(stu1, "name"))  # getattr方法获取一个实例中属性的直值
print(getattr(stu1, "securiteSkill", "没有秘技"))  # 获取一个不存在属性,如果没有指定默认值则会报错
print(getattr(stu1, "run"))
setattr(stu1, "securiteSkill", "独家秘技")  # 给对象设置属性
print(stu1.securiteSkill)
delattr(stu1, "securiteSkill")  # 删除属性 如果不存在则会报错

# 导入模块补充
# __import__("moduleName")  # 通过字符串导入模块,字符串不接受 a.b.c的分层,返回值只返回顶级对象
# from packageName.moduleNamee import *
# 该种导入会导入模块中的方法,但python不会导入 _method 这种方法
# 但可用强制导入 from packageNmae.moduleName import _method

# import importlib
# t=importlib.import_module("a.b.t")
# t.method()
# 使用importlib模块用字符串进行导入可用实现直接导入模块,调用方法
print(Student.__dict__)  # 并不是内置方法的全部
print(dir(Student))  # 获取全部的内置属性或方法


# ['__abstractmethods__', '__class__', '__delattr__', '__dict__',
#  '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__',
#  '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__',
#  '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
#  '__setattr__', '__sizeof__', '__str__',
#  '__subclasshook__', '__weakref__', '_abc_impl', 'run']
class Teacher(Person):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __getattr__(self, item):
        print("getattr方法被执行:----------------->", item)

    def __setattr__(self, key, value):
        print("setattr方法执行------------------------------>",key,value)
        self.__dict__[key] =value


    def run(self):
        print("%s is running" %self.name)


teacher1 = Teacher("buluse", 50)  # 生成实例时 setattr方法就会被执行

print(teacher1.abc) # 当调用不存在的属性值是 会出发 __getattr__方法
teacher1.skill = "weblogic"
print(teacher1.name,teacher1.age)
### Python反射机制及其使用 #### 什么是反射? 在计算机科学中,反射是一种允许程序在运行时检查和操作自身的特性。具体到 Python 中,反射指的是能够动态地访问或修改对象的属性、方法以及其他组件的能力[^2]。 #### 如何在 Python 中使用反射Python 提供了一些内置函数用于实现反射功能,这些工具可以帮助开发者动态地获取的信息或者执行特定的操作: 1. **`getattr()`**: 获取指定名称的对象属性。 ```python class Children: @staticmethod def drink(value): print(f"Drinking {value}") func = getattr(Children, "drink") # 动态获取名为 'drink' 的方法 func(1) # 调用该方法 ``` 2. **`hasattr()`**: 判断某个对象是否有指定的属性或方法。 ```python has_drink_method = hasattr(Children, "drink") print(has_drink_method) # 输出 True 或 False ``` 3. **`setattr()`**: 设置对象的属性值。 ```python setattr(Children, "age", 10) print(Children.age) # 输出设置的 age 属性值 ``` 4. **`delattr()`**: 删除对象的属性。 ```python delattr(Children, "age") try: print(Children.age) except AttributeError as e: print(e) # 如果删除成功,则会抛出异常 ``` 5. **`dir()`**: 返回对象的所有属性和方法列表(不包括私有成员)。 ```python attributes_and_methods = dir(Children) print(attributes_and_methods) # 打印所有可访问的属性和方法名 ``` 6. **`type()` 和 `isinstance()`**: 检查对象型。 ```python obj_type = type(instance) is_child_instance = isinstance(instance, Children) print(obj_type) # 输出 <class '__main__.Children'> print(is_child_instance) # 是否为子实例 ``` 7. **通过字符串动态创建实例**: 结合 `globals()` 函数可以从字符串形式的类名创建其实例。 ```python class_name = "MyClass" args = ("Alice", ) if class_name in globals(): class_object = globals()[class_name] instance = class_object(*args) # 创建实例 instance.say_hello() # 调用方法 else: print(f"Class {class_name} not found.") ``` 8. **元编程**: 元是更高级别的概念,它可以用来控制的创建过程,并且可以通过反射的方式增强的功能[^4]。 ```python class Meta(type): def __new__(cls, name, bases, dct): new_dct = {} for attr_name, attr_value in dct.items(): if callable(attr_value): new_dct[attr_name.upper()] = attr_value # 将所有方法转成大写名字 else: new_dct[attr_name] = attr_value return super().__new__(cls, name, bases, new_dct) class Example(metaclass=Meta): def test_function(self): pass example = Example() upper_func = getattr(example, "TEST_FUNCTION") # 方法名被转换成了大写 print(upper_func) # 输出对应的函数对象 ``` --- ### 总结 上述内容展示了如何利用 Python反射机制来动态操作和对象。无论是简单的属性读取还是复杂的元编程,都可以借助于反射完成更加灵活的设计模式][^[^23]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值