python -----类反射

#反射
#描述:反射就是指在程序运行时,动态的去确定对象的类型,并且可以通过字符串的形式去调用对应的属性
# ,方法,导入模块,是一种基于字符串的事情驱动
# class User:
# def __init__(self,):
# self.username='wang'
# self.userpwd=123
# obj1=User()
#我们平时使用方式,都是这样
# content=input('>>>:')
# if content=='username':
# print(obj1.username)
# elif content=='price':
# print(obj1.userpwd)
#但是上面的方法,我们如果调用成百上千的方法和属性,所以就有了反射这种方法
#python 提供了几个内置函数来这种事情 getattr(), hasattr()
# 对象的反射
# getattr(对象,字符串形式属性或方法名称)返回对象总属性名对应的值
# hasattr(对象,字符串形式属性或方法名称) 返回的是一个boo1 值,判断对象中是否存在属性
# 反射属性
# val=getattr(对象,'属性名') val就是属性的值
# 增加
class User:
def __init__(self,):
self.username='wang'
self.userpwd=123
obj1=User()
content=input('>>>:')
if hasattr(obj1,content): # 判断obj1对象中是否存在改属性
ret=getattr(obj1,content) # 对象和输入的字符串
print(ret)
# 反射方法 :方法的反射如果我们使用上面属性的反射的,会有问题;属性是不用加括号,但方法必须加括号才能返回
#callable() # 判断参数是否可以调用

class User:
def __init__(self,):
self.username='wang'
self.userpwd=123
def show__show(self):
print(self.username,self.userpwd)
obj1=User()
content=input('>>>:')
if hasattr(obj1,content): # 判断obj1对象中是否存在改属性
ret=getattr(obj1,content) # 对象和输入的字符串
if callable(ret): # 判断ret是否可调用,因为有可能是一个内存地址
ret()
else:
print(ret)
# 类的反射
#举例;
class A:
country='china'
print(getattr(A,'country'))
# 不但对类反射,类变量也可以反射
# 模块反射
import time
print(time.time)
print(getattr(time,'time')())
#反射应用的综合实例:
import  pickle
class Account:
opt_lst=[('登录','login'), ('注册','regiest' ),('退出','exit')]
def __init__(self):
self.dic={'username':'','userpwd':'' } # 构建字典格式: dic{ id: {username:'',userpwd:''}}
def login(self):
username=input('请输入用户:').strip()
userpwd=input('请输入密码:').strip()
with open('usernamelist',mode='rb') as f:
self.dic=pickle.load(f)
print(self.dic)
if username==self.dic['username'] and userpwd==self.dic['passwd']:
print('登录成功')
else:
print('用户名或者密码密码错误')
def regiest(self):
while True:
username=input("请输入用户名:").strip()
with open('usernamelist',mode='rb') as f:
try:
self.dic=pickle.load(f)
except:EnvironmentError
if username not in self.dic['username']:
while True:
userpwd=input("请输入用户密码:").strip()
userpwd2=input('请再次输入密码:').strip()
if userpwd==userpwd2:
self.dic.update(username=username,userpwd=userpwd)
with open('usernamelist',mode='ab') as f:
pickle.dump(self.dic,f)
break
else:
print('二次密码输入不一致,请重试输入秘密')
return True
else:
print('请更换其他用户名进行注册')
def run(self):
while True:
for index,lst in enumerate(Account.opt_lst,1):
print( Account.opt_lst[0][0],index)
num=int(input('请输入相关选择:').strip())
if hasattr(obj, Account.opt_lst[num - 1][1]):
getattr(obj, Account.opt_lst[num - 1][1])()

if __name__=='__main__':
obj=Account()
obj.run()
原文地址:https://www.cnblogs.com/pushuiyu/p/12577854.html