反射(getattr、setattr、setattr、delattr)

利用反射查找类中的属性或方法
class A:
    def __init__(self,name,attr):
        self.name = name
        self.attr = attr
    def ashow(self):
        print('hello world')
a = A('alex','dog')
print(hasattr(a,'attr'))
print(hasattr(a,'noattr'))
print(getattr(a,'attr'))
print('-----------------------')
print(hasattr(a,'ashow'))
print(getattr(a,'ashow'))
getattr(a,'ashow')()

执行结果:
True
False
dog
-----------------------
True
<bound method A.ashow of <__main__.A object at 0x00000000025A5550>>
hello world
利用反射查看模块中的变量和方法、本文件中的变量、函数、类
import os
import math
from sys import modules
a = 1
class A:pass
def func():pass
if hasattr(math,'pi'):
    print(getattr(math,'pi'))
if hasattr(os,'path'):
    print(getattr(os,'path'))
if hasattr(modules[__name__],'a'):
    print(getattr(modules[__name__],'a'))
if hasattr(modules[__name__],'A'):
    print(getattr(modules[__name__],'A'))
if hasattr(modules[__name__],'func'):
    print(getattr(modules[__name__],'func'))
执行结果:
3.141592653589793
<module 'ntpath' from 'C:\\Users\\Administrator\\venv\\oldboy\\lib\\ntpath.py'>
1
<class '__main__.A'>
<function func at 0x0000000001DC4730>

hasattr()和getattr()使用形式都是 函数名(命名空间,字符串),hasattr返回True或False,getattr返回与字符串同名的对象(属性、方法或类)
getattr(命名空间,'key') == 命名空间.key
setattr、delattr方法
class Student:
    def __init__(self,name):
        self.name = name
st_a =Student('lv')
print(st_a.__dict__)
setattr(st_a,'sex',30)
print(st_a.__dict__)
delattr(st_a,'sex')
print(st_a.__dict__)
#执行结果:
{'name': 'lv'}
{'name': 'lv', 'sex': 30}
{'name': 'lv'}

class Student:
    def __init__(self,name):
        self.name = name
st_a =Student('lv')
print(Student.__dict__)
setattr(Student,'country','China')
print(Student.__dict__)
delattr(Student,'country')
print(Student.__dict__)
# #执行结果:
{ ...'__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}
{ ...'__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None, 'country': 'China'}
{ ...'__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}

setattr的用法:setattr(命名空间,变量名,变量值),其中命名空间可以是对象、类、模块、本文件等,变量名必须是字符串格式,变量值可以是任意类型;



 
 



posted @ 2018-11-26 22:05  海予心  阅读(141)  评论(0编辑  收藏  举报