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'
    

      

  • 相关阅读:
    Linux 内核剖解(转)
    计算机系统的分层结构
    Linux学习之路三:重要概念之Linux系统层次结构
    库函数与系统调用的联系与区别
    库函数与系统调用
    库函数调用和系统调用的区别
    标准库函数和系统调用的区别
    关于Linux操作系统层次结构分析
    linux标准输入输出
    C语言的标准输入输出
  • 原文地址:https://www.cnblogs.com/iexperience/p/9206485.html
Copyright © 2011-2022 走看看