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

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

相关推荐
程序员的世界你不懂4 小时前
Appium+python自动化(八)- 认识Appium- 下章
python·appium·自动化
恸流失5 小时前
DJango项目
后端·python·django
Julyyyyyyyyyyy6 小时前
【软件测试】web自动化:Pycharm+Selenium+Firefox(一)
python·selenium·pycharm·自动化
蓝婷儿6 小时前
6个月Python学习计划 Day 15 - 函数式编程、高阶函数、生成器/迭代器
开发语言·python·学习
love530love6 小时前
【笔记】在 MSYS2(MINGW64)中正确安装 Rust
运维·开发语言·人工智能·windows·笔记·python·rust
水银嘻嘻7 小时前
05 APP 自动化- Appium 单点触控& 多点触控
python·appium·自动化
狐凄7 小时前
Python实例题:Python计算二元二次方程组
开发语言·python
烛阴8 小时前
Python枚举类Enum超详细入门与进阶全攻略
前端·python
Mikhail_G9 小时前
Python应用函数调用(二)
大数据·运维·开发语言·python·数据分析
weixin_4723394610 小时前
使用Python提取PDF元数据的完整指南
java·python·pdf