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"))

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

相关推荐
万化冥合35 分钟前
怎么批量把 Word 转 PDF?
python·pdf·c#·word
~城南花已开~40 分钟前
Redfish 事件接收服务搭建指南(Ubuntu Server 实测)
linux·服务器·python·ubuntu
fengyangaiGEO41 分钟前
如何通过GEO优化实现外贸B2B询盘增长?
人工智能·python
jianxuan1 小时前
Spring Boot + Maven 接入 Allatori:从普通打包到可选混淆发布
spring boot·python·maven
不一样的故事1261 小时前
Prompt 工程(Prompt Engineering)
前端·人工智能·python
我命由我123451 小时前
6-2.Python 异常处理 - 异常捕获(捕获指定异常、常见异常类型、异常信息)
java·运维·开发语言·python·http·https·java-ee
zh路西法1 小时前
【模型式强化学习】(三):MBPO——短轨迹生成与模型数据驱动的策略优化
python·强化学习·pe·sac·pets·mbpo·mbrl
Angeldream1231 小时前
第 9 章 医学影像项目实战
大数据·图像处理·人工智能·python·医学影像处理
ZhengEnCi1 小时前
一亿条数据取前100条完全指南:从全量排序到分块流式最小堆的4种解法实测
python·算法·排序算法
2601_967979121 小时前
AccessControl 5.4 macOS Python 3.9 版本安装包
python·macos·security·accesscontrol·permissions