zoukankan      html  css  js  c++  java
  • python 反射

    通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法

    1.hasattr(对象名,属性或方法名):

    判断object中有没有一个name字符串对应的方法或属性
    class dog(object):
        '''hasattr方法是判断类中是否有指定的方法'''
        def __init__(self,name):
            self.name=name
        def eat(self):
            print '%s is ....'%self.name
    d=dog('xx')
    c=raw_input('---:')
    # e=''.join(c)
    print (hasattr(d, c))   #hasattr(对象名,属性名)
    
    结果:
    ---:eat
    True
    

    2.getattr(对象名, 方法名):返回对象中方法在内存中的地址

    class dog(object):
        
        def __init__(self,name):
            self.name=name
        def eat(self):
            print '%s is ....'%self.name
    d=dog('xx')
    c=raw_input('---:')
    # e=''.join(c)
    print (hasattr(d, c))   #hasattr(对象名,属性名)
    print getattr(d, c)   #返回方法在内存中的地址
    getattr(d, c)()    #eat()
    
    结果:
    ---:eat
    True
    <bound method dog.eat of <__main__.dog object at 0x02376AB0>>
    xx is ....
    

    3.setattr(对象名,字符串,方法名);将类定义之外的方法可以被实例化对象使用,将方法名赋值给对象名.字符串。

    class dog(object):
        '''setattr方法是将类之外的方法可以被实例化对象使用'''
        def __init__(self,name):
            self.name=name
        def eat(self):
            print '%s is ....'%self.name
    def bul(self):
        print "bul....%s..."%self.name
    
    d=dog('xx')
    c=raw_input('---:')
    setattr(d,c,bul)  #d.c=bul  将方法名赋予d.c
    p=getattr(d, c)   #得到方法bul的内存地址
    p(d)    #使用方法bul  ,也可以这样写d.ta(d)
    
    结果:
    ---:ta
    bul....xx...
    

    4. delattr删除类中指定的方法或属性

    class dog(object):
        '''delattr删除类中的方法或属性'''
        def __init__(self,name):
            self.name=name
        def eat(self):
            print '%s is ....'%self.name
    
    d=dog('xx')
    c=raw_input('---:')
    delattr(d,c )  #删除指定的方法或属性
    print d.name
    
    结果:
    ---:name
    Traceback (most recent call last):
      File "D:softeclipse-workspaceceshilianx1.py", line 540, in <module>
        print d.name
    AttributeError: 'dog' object has no attribute 'name'
    

      

  • 相关阅读:
    Markdown基本语法
    Hexo 集成 Gitalk 评论系统
    hexo添加百度统计
    tf.nn.softmax
    tf.InteractiveSession()与tf.Session()
    归一化、标准化、正则化的区别
    感受野的概念
    CNN中的low-level feature 与high-level feature
    安装vncserver后导致Ubuntu循环登录进入不了桌面的问题原因及解决办法
    python3 + Tensorflow + Faster R-CNN训练自己的数据
  • 原文地址:https://www.cnblogs.com/iexperience/p/9206485.html
Copyright © 2011-2022 走看看