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程序设计有所帮助。
相关推荐
chuckchen 2020-10-31
Will0 2020-10-12
Dreamhome 2020-10-09
xirongxudlut 2020-09-28
星辰大海的路上 2020-09-13
chaochao 2020-08-31
猪猪侠喜欢躲猫猫 2020-08-17
快递小可 2020-08-16
shengge0 2020-07-26
巩庆奎 2020-07-21
张文倩数据库学生 2020-07-19
xirongxudlut 2020-07-18
Ericbig 2020-07-18
kyelu 2020-07-09
liangzhouqu 2020-07-07
GuoSir 2020-06-28
chaigang 2020-06-27
pythonxuexi 2020-06-25