Python3.6简单反射操作示例
本文实例讲述了Python3.6简单反射操作。分享给大家供大家参考,具体如下:
# -*- coding:utf-8 -*- #!python3 # ----------------------- # __Author : tyran # __Date : 17-11-13 # ----------------------- class Base: def __init__(self): self.name = 'aaa' self.age = 18 def show(self): print(self.age) # 通过getattr()找到对象的成员 base = Base() v = getattr(base, 'name') print(v) # aaa func1 = getattr(base, 'show') func1() # 18 # 通过hasattr()查找成员是否存在 print(hasattr(base, 'name')) # True print(hasattr(base, 'name1')) # False # 通过setattr()给对象添加成员 setattr(base, 'k1', 'v1') print(base.k1) delattr(base, 'k1') # v1 # print(base.k1) 报错AttributeError: 'Base' object has no attribute 'k1' # ------------------------------------------------------------------------- # Class也是一个对象 class ClassBase: sex = 'male' def __init__(self): self.name = 'aaa' self.age = 11 @staticmethod def show(): print('I am static') @classmethod def c_method(cls): print(cls.sex) sex_value = getattr(ClassBase, 'sex') print(sex_value) s_func = getattr(ClassBase, 'show') s_func() c_func = getattr(ClassBase, 'c_method') c_func() # 这些都没问题 setattr(ClassBase, 'has_girlfriend', True) # 添加静态成员 print(ClassBase.has_girlfriend) # True # ---------------同理,模块也是对象------------- # 我新建了一个模块s1.py,我把内容复制下来 # class S1: # def __init__(self): # self.name = 'aaa' # self.age = 22 # # def show(self): # print(self.name) # print(self.age) # # # def func1(): # print('page1') # # # def func2(): # print('page2') # 一个类,两函数 import s1 s1_class = getattr(s1, 'S1', None) if s1_class is not None: c1 = s1_class() c1.show() # aaa # 22 getattr(s1, 'func1')() # page1 f2 = 'func2' if hasattr(s1, f2): getattr(s1, 'func2')() # page2
注释中说明的s1.py如下:
# -*- coding:utf-8 -*- #!python3 class S1: def __init__(self): self.name = 'aaa' self.age = 22 def show(self): print(self.name) print(self.age) def func1(): print('page1') def func2(): print('page2') # 一个类,两函数
程序运行结果:
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
赞 (0)