欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python3.6简单反射操作示例

程序员文章站 2023-09-07 20:33:44
本文实例讲述了Python3.6简单反射操作。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!python3 # ----...

本文实例讲述了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')
# 一个类,两函数

程序运行结果:

Python3.6简单反射操作示例

更多关于Python相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》及《》

希望本文所述对大家Python程序设计有所帮助。