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

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

相关推荐
ㄣ知冷煖★几秒前
基于openEuler操作系统的图神经网络应用开发:以Cora数据集节点分类为例的研究与实践
python
祝余Eleanor7 分钟前
Day32 深入理解SHAP图
人工智能·python·机器学习
int WINGsssss28 分钟前
【无标题】
pytorch·分布式·python
q_302381955639 分钟前
Python实现基于多模态知识图谱的中医智能辅助诊疗系统:迈向智慧中医的新篇章
开发语言·python·知识图谱
我的xiaodoujiao1 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 31--开源电商商城系统项目实战--加入购物车、提交订单测试场景
python·学习·测试工具·pytest
梨落秋霜1 小时前
Python入门篇【输入input】
开发语言·python
Buxxxxxx1 小时前
DAY 34 模块和库的导入
开发语言·python
qq_356196951 小时前
day30函数专题1:函数定义和参数@浙大疏锦行
python
haiyu_y1 小时前
Day 27 通用机器学习流水线
人工智能·python·机器学习