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

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

相关推荐
虎虎(_ _)。゜zzZ8 小时前
关于字典中的解包问题
python
全栈弄潮儿²⁰²⁴8 小时前
Python实战第2期: 变量与数据类型
python·变量·数据类型·python实战
程序员yu9 小时前
会编网络:别被入门教程骗了,Python实用能力不在语法本身
开发语言·python·学习·算法
鬼手点金9 小时前
opencode组件详解-安装方式
人工智能·python·优化器·分析器·nanogpt
Bruce_Liuxiaowei9 小时前
Python 字典默认值完全指南:从 KeyError 到 defaultdict
开发语言·数据结构·python·字典
数据杂坛9 小时前
【Python程序开发系列】一文搞清楚Gunicorn以及和Nginx的区别
python·nginx·gunicorn
zjh9005309 小时前
Visual C++ 2010 安装使用完整包:高手秘籍
python
Allen_LVyingbo9 小时前
信息化部门在AI时代的编程转移路径分析(上)
人工智能·python·算法·健康医疗·数据库开发·时序数据库·数据库架构
用户0332126663679 小时前
Python 实现 Word/TXT 互转:附完整代码
python
常山云栈10 小时前
Anaconda和uv的区别是什么?
python·anaconda·uv