Python 反射

2023-12-13 09:33:04

Python 反射是什么?

学习了几天,做个总结留给自己看。

感觉跟 SQL 入门要掌握的原理一样,Python 反射看起来也会做4件事,“增删查获”

增 - 增加属性,方法?

setattr

删 - 删除属性,方法

delattr

查 - 查找是否存在属性,方法

hasattr

获 - 获取属性,方法

getattr

举个例子

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

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

文章来源:https://blog.csdn.net/numen610/article/details/134945885
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。