Python的反射

通过字符串的形式操作对象的属性

python 复制代码
class Person(object):
    def __init__(self,name,age) -> None:
        self.name=name
        self.age=age
    def walking(self):
        print("walking......")

获取对象的属性

python 复制代码
p=Person("Recardo",12)
# 获取队形的name属性
a=getattr(p,"name")
# Recardo
print(a)

为对象添加static的属性

python 复制代码
p=Person("Recardo",12)
# 添加static 属性的变量
setattr(p,"yanling","show me the flowers")
# show me the flowers
print(p.yanling)

为对象添加方法

python 复制代码
p=Person("Recardo",12)
#对实例添加方法
def talking(self):
    print(self.name,"is talking")
# 为p对象添加名为speak的方法
setattr(p,"speak",talking)
# Recardo is talking
p.speak(p)

对Student类添加方法

python 复制代码
p=Person("Recardo",12)
#对实例添加方法
def talking(self):
    print(self.name,"is talking")
#对Person类添加方法
setattr(Person,"speak2",talking)
# p对象调用Person类的方法
# Recardo is talking
p.speak2()

删除对象的变量

python 复制代码
p=Person("Recardo",12)
# 相当于del p.age
delattr(p,"age") 
# AttributeError: 'Person' object has no attribute 'age'
print(p.age)

输入对象的方法名,对象执行方法

python 复制代码
class Person(object):
    def __init__(self,name,age) -> None:
        self.name=name
        self.age=age
    def walking(self):
        print(self.name," is walking......")

p=Person("Recardo",12)
user_command=input(">>:").strip()
if hasattr(p,user_command):
    func=getattr(p,user_command)
    func()
"""
>>:walking
Recardo  is walking......
"""

__name__属性

reflect2.py

python 复制代码
"""
reflect2.py
magical reflect2
__name__
反射一个.py文件下的字符串的属性
"""

class Person(object):
    def __init__(self,name,age) -> None:
        self.name=name
        self.age=age
    def walking(self):
        print("walking......")


print("outside the __main__")
print(__name__)
#在被别的模块导入的时候,发挥作用,被导入时,__name__=="xxx.py"中的xxx
#不被导入时,__name__=="__main__"
if __name__=="__main__":
    print("inside the __main__")
    print(__name__)
"""
outside the __main__
__main__
inside the __main__
__main__
"""

此时,无论是main方法里面还是main方法外面,name__都等于__main

reflect4.py

python 复制代码
import reflect2 as r2

运行reflect4.py

控制台打印:

python 复制代码
outside the __main__
reflect2

此时,reflect2中的name是reflect2

夸文件反射

python 复制代码
# reflect4.py
# 导入reflect2.py
import reflect2 as r2

if hasattr(r2,"Person"):
    PersonClass=getattr(r2,"Person")
    p=PersonClass("ChenLuo",3)
    print(p.name)
    print(p.age)
    p.walking()

"""
运行结果:
outside the __main__
reflect2
ChenLuo
3
walking......
"""
相关推荐
yangzhi_emo7 分钟前
ES6笔记2
开发语言·前端·javascript
emplace_back1 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
jz_ddk1 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
萧曵 丶1 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
xiaolang_8616_wjl1 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
收破烂的小熊猫~1 小时前
《Java修仙传:从凡胎到码帝》第四章:设计模式破万法
java·开发语言·设计模式
蹦蹦跳跳真可爱5892 小时前
Python----OpenCV(图像増强——高通滤波(索贝尔算子、沙尔算子、拉普拉斯算子),图像浮雕与特效处理)
人工智能·python·opencv·计算机视觉
nananaij2 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
雷羿 LexChien2 小时前
从 Prompt 管理到人格稳定:探索 Cursor AI 编辑器如何赋能 Prompt 工程与人格风格设计(上)
人工智能·python·llm·编辑器·prompt