反射
用字符串数据类型的名字 来操作这个名字对应的函数实例变量绑定方法各种方法
1.反射对象的 实例变量
2.反射类的 静态变量/绑定方法/其他方法
3.模块中的 所有变量
被导入的模块
当前执行的py文件 - 脚本
class Person:
def __init__(self,name ,age):
self.name = name
self.age = age
def qqxing(self):
print('qqxing')
alex = Person('alex',83)
ret = getattr(alex,'name')
print(ret) #alex
s = getattr(alex,'qqxing')
s()#qqxing
#反射模块中的 所有变量、方法
# import a
# print(a.Wechat)
# print(a.Alipay)
# # 对象名.属性名 ==> getattr(对象名,'属性名')
# # a.Alipay ==> getattr(a,'Alipay')
# print(getattr(a, 'Alipay'))
# print(getattr(a, 'Wechat'))
--------------------------------
import a
import sys
print(sys.modules)
# print(sys.modules)
# print(sys.modules['a'].Alipay)
# print(a.Alipay)
# print(getattr(a,'Alipay'))
# print(getattr(sys.modules['a'],'Alipay'))
# wahaha = 'hahaha'
# print(getattr(sys.modules['__main__'],'wahaha'))
#sys.modules['__main__'] 本模块
class Payment:pass
class Alipay(Payment):
def __init__(self,name):
self.name = name
def pay(self,money):
dic = {'uname':self.name,'price':money}
print('%s通过支付宝支付%s钱成功'%(self.name,money))
class WeChat(Payment):
def __init__(self,name):
self.name = name
def pay(self,money):
dic = {'username':self.name,'money':money}
print('%s通过微信支付%s钱成功'%(self.name,money))
class Apple(Payment):
def __init__(self,name):
self.name = name
def pay(self,money):
dic = {'name': self.name, 'number': money}
print('%s通过苹果支付%s钱成功' % (self.name, money))
class QQpay:
def __init__(self,name):
self.name = name
def pay(self,money):
print('%s通过qq支付%s钱成功' % (self.name, money))
import sys
def pay (name,price,kind):
class_name = getattr(sys.modules['__main__'],kind)
obj = class_name(name)
obj.pay(price)
# if kind == 'Wechat':
# obj = WeChat(name)
# elif kind == 'Alipay':
# obj = Alipay(name)
# elif kind == 'Apple':
# obj = Apple(name)
# obj.pay(price)
# pay('alex',400,'WeChat')
# pay('alex',400,'Alipay')
# pay('alex',400,'Apple')
# pay('alex',400,'QQpay')
反射的另一个函数 hasattr(一般成对使用)
class A:
Role = '治疗'
def __init__(self):
self.name = 'alex'
self.age = 84
def func(self):
print('wahahaha')
return 666
a = A()
print(hasattr(a,'sex'))#False 是否可反射到
print(hasattr(a,'age'))#True
print(hasattr(a,'func'))#True
if hasattr(a,'func'):
if callable(getattr(a,'func')): #callable 是否可被调用(既判断是否可以在后面加())
getattr(a,'func')()