Python 反射

Python 反射是什么?

学习了几天,做个总结留给自己看。

感觉跟 SQL 入门要掌握的原理一样,Python 反射看起来也会做4件事,"增删查获"

增 - 增加属性,方法

python 复制代码
setattr

删 - 删除属性,方法

python 复制代码
delattr

查 - 查找是否存在属性,方法

python 复制代码
hasattr

获 - 获取属性,方法

python 复制代码
getattr

举个例子

python 复制代码
class Student:
    city = "Shanghai"

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

    def hello_student(self):
        name = self.name
        print("你好: {}".format(name))


Jack = Student("Jack", 6, "123456789")

print(getattr(Student, 'city'))
print(hasattr(Student, "city"))
print(hasattr(Student, "hello_student"))
print(hasattr(Student, "hello_jack"))

getattr(Student, "my_info")()

setattr(Jack, "name", "Tom")
print(getattr(Jack, "name"))


def hello_student_new(self):
    name = self.name
    print("新朋好友你好: {}".format(name))


setattr(Jack, "my_name", hello_student_new)
getattr(Jack, "hello_student_new")()

delattr(Student, "city")
print(getattr(Student, 'city'))

delattr(Student, "name")
print(getattr(Student, "name"))

delattr(Student, "hello_student_new")
print(getattr(Student, "hello_student_new"))

这些例子基本涵盖了四种用法。

相关推荐
add45a3 分钟前
Python类型提示(Type Hints)详解
jvm·数据库·python
记忆张量MemTensor4 分钟前
AI 数据迁移指南|Claude 靠提示词搬家,MindDock 一键完整备份记忆
人工智能·python·开源·github·浏览器
移远通信8 分钟前
Helios SDK开发指南__入门应用代码编写
python
天远Date Lab8 分钟前
Python实战:基于天远二手车估值API构建企业车队资产数字化管理方案
大数据·人工智能·python
tryCbest8 分钟前
Python之FastAPI 开发框架(第三篇):高级特性与实战
开发语言·python·fastapi
BestOrNothing_20158 分钟前
Ubuntu 22.04 下使用 VS Code 搭建 ROS 2 Humble 集成开发环境
c++·vscode·python·ros2·ubuntu22.04
ZTLJQ20 分钟前
挖掘金矿:Python数据解析库完全解析
开发语言·python
ONE_SIX_MIX28 分钟前
lancedb 表名 编解码 与 转译 python
开发语言·python
2501_9454248029 分钟前
机器学习与人工智能
jvm·数据库·python
BatyTao30 分钟前
Python从零起步-Python函数
python