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

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

相关推荐
数据科学作家3 小时前
学数据分析必囤!数据分析必看!清华社9本书覆盖Stata/SPSS/Python全阶段学习路径
人工智能·python·机器学习·数据分析·统计·stata·spss
HXQ_晴天4 小时前
CASToR 生成的文件进行转换
python
java1234_小锋5 小时前
Scikit-learn Python机器学习 - 特征预处理 - 标准化 (Standardization):StandardScaler
python·机器学习·scikit-learn
Python×CATIA工业智造5 小时前
Python带状态生成器完全指南:从基础到高并发系统设计
python·pycharm
向qian看_-_5 小时前
Linux 使用pip报错(error: externally-managed-environment )解决方案
linux·python·pip
Nicole-----6 小时前
Python - Union联合类型注解
开发语言·python
Eric.5658 小时前
python advance -----object-oriented
python
云天徽上9 小时前
【数据可视化-107】2025年1-7月全国出口总额Top 10省市数据分析:用Python和Pyecharts打造炫酷可视化大屏
开发语言·python·信息可视化·数据挖掘·数据分析·pyecharts
THMAIL9 小时前
机器学习从入门到精通 - 数据预处理实战秘籍:清洗、转换与特征工程入门
人工智能·python·算法·机器学习·数据挖掘·逻辑回归
@HNUSTer9 小时前
Python数据可视化科技图表绘制系列教程(六)
python·数据可视化·科技论文·专业制图·科研图表