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

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

相关推荐
吴梓穆11 分钟前
Python 语法基础 函数
开发语言·python
Kobebryant-Manba19 分钟前
学习文本处理
开发语言·python
m0_6174939424 分钟前
PaddleOCR报错:OneDnnContext does not have the input Filter 解决方案汇总
python
李可以量化26 分钟前
量化迅投 QMT vs 聚宽 (JoinQuant)全面分析
python·量化·qmt·ptrade·聚宽
旅僧41 分钟前
运行UMI镜像
python
ellenwan202643 分钟前
期货跨期价差程序化怎么做:天勤 SP 合约与腿比例核对
python·区块链
月疯1 小时前
torch:expand和repeate的区别
开发语言·python·深度学习
顾林海1 小时前
Agent入门阶段-编程基础-Python:Python 开发环境与运行方式
python·agent·ai编程
叫我:松哥1 小时前
基于深度卷积神经网络的水果图片分类算法设计与实现,有ResNet50的迁移学习模型,准确率达95%
人工智能·python·神经网络·机器学习·分类·cnn·迁移学习
Orchestrator_me1 小时前
Python pip install报SSL错误
python·ssl·pip