def login(self, user_name, password): with open('./data/user.txt', 'r') as f3: users_infor = [eval(each.strip()) for each in f3.readlines()] for item in users_infor: if user_name == item['user_name'] and password == self.decrypted_password(item['user_password']): if item['user_role'] == 'admin': target_obj = Admin(item['user_id'], item['user_name'],item['user_password'], item['user_register_time'],item['user_role']) print(target_obj) return target_obj elif item['user_role'] == 'customer': target_obj = Customer(item['user_id'], item['user_name'], item['user_password'],item['user_register_time'], item['user_role'], item['user_email'], item['user_mobile']) return target_obj为什么我这段代码中的target_obj是空值
时间: 2024-03-22 13:39:30 浏览: 199
TXT_test.rar_test.txt文_监控文件夹_监控文件夹下的文件生成
你的代码中,如果输入的用户名和密码与用户信息匹配,会分别创建 Admin 或 Customer 对象并返回。但是如果用户名和密码不匹配,函数没有返回任何值,也就是没有匹配到用户时 target_obj 的值是空值 None。你可以在函数末尾添加一个默认的返回 None 语句,以保证 target_obj 有默认值。例如:
```
def login(self, user_name, password):
with open('./data/user.txt', 'r') as f3:
users_infor = [eval(each.strip()) for each in f3.readlines()]
for item in users_infor:
if user_name == item['user_name'] and password == self.decrypted_password(item['user_password']):
if item['user_role'] == 'admin':
target_obj = Admin(item['user_id'], item['user_name'],item['user_password'],
item['user_register_time'],item['user_role'])
print(target_obj)
return target_obj
elif item['user_role'] == 'customer':
target_obj = Customer(item['user_id'], item['user_name'],
item['user_password'],item['user_register_time'], item['user_role'],
item['user_email'], item['user_mobile'])
return target_obj
return None
```
这样当没有匹配到用户时,函数也会返回一个默认的空值 None。
阅读全文