Posted in Python onJune 14, 2018
本文实例讲述了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程序设计有所帮助。
Python3.6简单反射操作示例
- Author -
Tyran_U声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@