反射hasattr; getattr; setattr; delattr

hasattr(obj,name_str):#判断一个对象obj里面是否有对应的name_str字符串的方法,返回True或者False

getattr(obj,name_str):#根据字符串去获取对象里的对应方法的内存地址。
复制代码
class Dog(object):
    def __init__(self,name):
        self.name = name
    def eat(self,food):
        print('%s eating...:%s' %(self.name,food))
    def talk(self):
        print('%s talk 汪汪汪~!'% self.name)
d = Dog('NiuhanYang')
chose = input('想让狗干什么:\n\t\t>>:')
# print(hasattr(d,chose))
if hasattr(d,chose):#判断一个对象obj里面是否有对应的name_str字符串的方法,返回True或者False
    # getattr(d,chose)('粑粑')
    func = getattr(d,chose)  #根据字符串去获取对象里的对应方法的内存地址。
    # func('粑粑')
    func()
hasattr和getattr代码实例
复制代码

setattr(obj,'y',v) #根据字符串y,去设置一个obj的一个y属性或y方法;v就是y的值(内存地址)

复制代码
class Dog(object):
    def __init__(self,name):
        self.name = name
    def eat(self,food):
        print('%s eating...:%s' %(self.name,food))

d = Dog('NiuhanYang')
chose = input('想让狗干什么:\n\t\t>>:')
# print(hasattr(d,chose))
if hasattr(d,chose):#判断一个对象obj里面是否有对应的name_str字符串的方法,返回True或者False
    # getattr(d,chose)('粑粑')
    func = getattr(d,chose)  #根据字符串去获取对象里的对应方法的内存地址。
    func('粑粑')
    # func()
else:
    setattr(d,chose,22) #假定 chose输入的为age,d对象中的类中没有这个方法或者属性,就给他赋值22
    print(d.age)
setattr
复制代码
想让狗干什么:
        >>:age
22
输出

 delattr(obj,'str') #根据字符串‘str’去删除obj中的这个方法或者属性

复制代码
class Dog(object):
    def __init__(self,name):
        self.name = name
    def eat(self,food):
        print('%s eating...:%s' %(self.name,food))

d = Dog('NiuhanYang')
chose = input('想让狗干什么:\n\t\t>>:')
# print(hasattr(d,chose))
if hasattr(d,chose):#判断一个对象obj里面是否有对应的name_str字符串的方法,返回True或者False
    # getattr(d,chose)('粑粑')
    func = getattr(d,chose)  #根据字符串去获取对象里的对应方法的内存地址。
    func('粑粑')
    # func()
else:
    setattr(d,chose,22) #假定 chose输入的为age,d对象中的类中没有这个方法或者属性,就给他赋值22
    print(d.age)
delattr(d,chose)
print(d.age)
示例代码
复制代码
复制代码
想让狗干什么:
        >>:age
22
Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/Python3_study/day6/反射.py", line 23, in <module>
    print(d.age)
AttributeError: 'Dog' object has no attribute 'age'
示例代码输出
复制代码

 

posted on   zhangmingda  阅读(123)  评论(0编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示