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'
    

      

  • 相关阅读:
    global mapper合并多个tif影像
    arcgis 10.2 licence manager无法启动
    Error C2079 'CMFCPropertySheet::m_wndOutlookBar' uses undefined class 'CMFCOutlookBar'
    家里的技嘉B360主板win10 uefi系统安装
    vc 6.0项目转为vs 2017项目遇到 的问题
    PPT学习笔记
    git拉取分支
    将本地源码推向gitee码云
    java反编译工具使用记录
    node.js install and cecium apply
  • 原文地址:https://www.cnblogs.com/iexperience/p/9206485.html
Copyright © 2011-2022 走看看