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'
    

      

  • 相关阅读:
    JS中数组去除重复的方法
    ember.js里的实用方法
    Ember入门指南——教程目录
    如何解决问题?
    Web前端开发工程师基本要求
    (转)轻松学习JavaScript三:JavaScript与HTML的结合
    (转)JavaScript二:JavaScript语言的基本语法要求
    HTML的checkbox和radio的美化
    C#串口通信—向串口发送数据,同步接收返回数据
    C#生成验证码
  • 原文地址:https://www.cnblogs.com/iexperience/p/9206485.html
Copyright © 2011-2022 走看看