def register_admin(self): adm_id = uop.generate_unique_user_id() adm_unm = 'daddy_daddy' adm_pswd = 'daddy' adm_time = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S") adm_role = 'admin' register = Admin(adm_id,adm_unm,adm_pswd,adm_time,adm_role) str_register = eval(str(register)) str_register['user_password'] = uop.encrypt_password(adm_pswd) with open('./data/user.txt','w') as f1: f1.write(str_register + '\n')为什么我这里会有AttributeError: 'str' object has no attribute 'user_id'?
时间: 2024-03-22 20:38:46 浏览: 22
在你的代码中,`str_register`是一个字符串类型的对象,而非Admin对象。你在将`register`对象转换为字符串时,使用了`eval()`函数,这个函数将字符串转换为Python对象,但是这里的字符串并不符合Python对象的格式,因此会出现错误。
正确的做法应该是将`register`对象转换为字典类型的对象,然后再将这个字典对象转换为字符串,这样就可以正确地写入到文件中了。可以按照以下方式修改你的代码:
```python
def register_admin(self):
adm_id = uop.generate_unique_user_id()
adm_unm = 'daddy_daddy'
adm_pswd = 'daddy'
adm_time = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
adm_role = 'admin'
register = Admin(adm_id, adm_unm, adm_pswd, adm_time, adm_role)
register_dict = {
'user_id': register.user_id,
'user_name': register.user_name,
'user_password': uop.encrypt_password(adm_pswd),
'user_register_time': register.user_register_time,
'user_role': register.user_role
}
str_register = str(register_dict)
with open('./data/user.txt', 'w') as f1:
f1.write(str_register + '\n')
```
这样就可以正确地将Admin对象写入到文件中了。注意,这里使用的是字典类型的对象,而非字符串类型的对象。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)