zoukankan      html  css  js  c++  java
  • 反射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('想让狗干什么:
    		>>:')
    # 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('想让狗干什么:
    		>>:')
    # 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('想让狗干什么:
    		>>:')
    # 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'
    示例代码输出
  • 相关阅读:
    C语言寒假大作战01
    C语言|博客作业12-学期总结
    第一次作业
    C语言|博客作业11
    C语言|博客作业10
    Centos7上安装 sqlmap 所经历的坑
    软件工程1916|W(福州大学)_助教博客】助教总结
    软件工程1916|W(福州大学)_助教博客】个人总结作业(第12次)成绩公示
    团队作业第五次(第8次)—项目系统设计与数据库设计成绩排名
    需求分析课堂答辩问题汇总
  • 原文地址:https://www.cnblogs.com/zhangmingda/p/9163729.html
Copyright © 2011-2022 走看看