python--反射

#!/usr/bin/env python
# -*- encoding:utf-8 -*-
"""
    反射:根据字符串的形式去对象(某个模块/类)中操作其成员
"""
# 根据字符串导入模块
py01 = __import__("0121.py01ref", fromlist=True)

# 根据字符串获取模块中的方法
func = getattr(py01, 'eat')
f = func()
print(f, type(f))

# 根据字符串获取模块中的类
cls = getattr(py01, 'Father')
print(cls, type(cls))
# 通过类调用静态方法
cls.eat()
# 创建对象
father = cls()
print(father, type(father))
# 通过对象调用方法
father.eat()

# 添加属性
setattr(father, 'age', 22)
# 判断属性是否存在
if hasattr(father, 'age'):
    print(father.age)

# 删除属性
delattr(father, 'age')
if hasattr(father, 'age'):
    print(father.age)
else:
    print('no attribute')

 

posted on 2018-01-23 11:00  jovelove  阅读(83)  评论(0)    收藏  举报