"""
反射
"""
"""
反射:通过字符串的形式操作对象相关的属性。
python中的一切事物都是对象(都可以使用反射)
反射组合函数:
hasattr、getattr、setattr、delattr
"""
class Person:
animal = '高级动物'
def __init__(self, name, age):
self.name = name
self.age = age
def work(self):
print('人需要工作啊')
albert = Person('albert', 17)
print(hasattr(albert, 'name'))
print(hasattr(albert, 'animal'))
print(hasattr(albert, 'sex'))
print(hasattr(albert, 'work'))
ret = getattr(albert, 'name')
print(ret)
ret2 = getattr(albert, 'work')
print(ret2)
ret2()
ret3 = getattr(albert, 'home', '没有此属性或方法')
print(ret3)
setattr(albert,'sex', '男')
setattr(albert, 'height', 187)
print(albert.__dict__)
delattr(albert, 'age')
print(albert.__dict__)
class Student:
sleep = '爱睡觉'
def __init__(self, name):
self.name = name
def homework(self):
return '每天好多作业啊'
if hasattr(Student, 'sleep'):
print(getattr(Student, 'sleep'))
if hasattr(Student, 'homework'):
s1 = Student('don')
res = getattr(s1, 'homework')()
print(res)
res1 = getattr(Student, 'homework')(s1)
print(res1)
"""
reflect_test.py模块内容:
name = 'reflect_don'
def hello():
print('Hello World!')
class Animal:
language = '很多'
def __init__(self, name):
self.name = name
def func(self):
print('看看')
"""
import reflect_test
print(hasattr(reflect_test, 'name'))
ret = getattr(reflect_test, 'name')
print(ret)
getattr(reflect_test, 'hello')()
r1 = getattr(reflect_test, 'Animal')
ani = r1('don')
print(ani.__dict__)
print(getattr(reflect_test.Animal, 'language'))
obj = getattr(reflect_test, 'Animal')('hugu')
print(obj.name)
today = '今天是个好天气啊'
def play():
print('一起去玩耍啊')
import sys
print(sys.modules[__name__])
print(getattr(sys.modules[__name__], 'today'))
getattr(sys.modules[__name__], 'play')()
|