一、反射对象的实例变量/绑定方法
import time
class Perosn():
def __init__(self, name, birth):
self.name = name
self.birth = birth
@property
def age(self):
return time.localtime().tm_year - self.birth
mkc = Perosn('mkc', 1993)
print(mkc.age)
# 反射的用法:
ret = getattr(mkc, 'age')
print(ret)
ret1 = getattr(mkc, 'name')
print(ret1)
二、反射类的静态/其它方法
class Person():
type = '人类'
def __init__(self, name, birth):pass
print(Person.type)
print(getattr(Person, 'type'))
三、反射模块的任意变量
用法:getattr(模块名, '变量名')
四、反射本模块/脚本中任意变量
import sys
class Person():
type = '人类'
def __init__(self, name, birth):
self.name = name
self.birth = birth
dic = {'name':'沐坤昌', 'age':28}
print(getattr(sys.modules['__main__'], 'dic'))
print(getattr(sys.modules['__main__'], 'Person'))