Python 了解类的属性(增加值)
我正在阅读Python速成课程,问题如下 9-5。登录尝试:向您的Python 了解类的属性(增加值),python,class,Python,Class,我正在阅读Python速成课程,问题如下 9-5。登录尝试:向您的用户添加一个名为登录尝试的属性 从练习9-3(第166页)开始上课。编写一个名为increment\u login\u attempts()的方法,将login\u attempts的值增加1 写 另一种方法称为reset\u login\u attempts(),它将login\u attempts的值重置为0 创建一个User类的实例,并调用increment\u login\u truments() 好几次。打印login\
用户添加一个名为登录尝试
的属性
从练习9-3(第166页)开始上课。编写一个名为increment\u login\u attempts()
的方法,将login\u attempts
的值增加1
写
另一种方法称为reset\u login\u attempts()
,它将login\u attempts
的值重置为0
创建一个User
类的实例,并调用increment\u login\u truments()
好几次。打印login\u尝试的值
,以确保该值已递增
正确,然后调用reset\u login\u attempts()
。再次打印登录\u尝试
确保已将其重置为0
我把这个类定义为
class User():
def __init__(self, first_name, last_name, gender, age):
"""
User inputs
"""
self.first_name = first_name
self.last_name = last_name
self.gender = gender
self.age = age
self.login_attempts = 0
def describe_user(self):
"""
Printing the users information
"""
print("User Name: ", self.first_name)
print("Last Name: ", self.last_name)
print("Gender: ", self.gender)
print("Age: ", self.age)
def increment_login_attempts(self):
'''
Increment the login attempts one by one, each time users try to enter
'''
self.login_attempts += 1
print("You have tried logging in", self.login_attempts, "times")
def reset_login_attempts(self):
'''
Resetting the logging attempts
'''
self.login_attempts = 0
print("Login Attempt has set to ", self.login_attempts)
user = User("Sean", "Dean", "Male", 19)
user.describe_user()
user.increment_login_attempts()
user.increment_login_attempts()
user.increment_login_attempts()
user.increment_login_attempts()
user.reset_login_attempts()
现在我的问题是这样的,
当我只写的时候
user = User("Sean", "Dean", "Male", 19)
user.describe_user()
user.increment_login_attempts()
它打印
User Name: Sean
Last Name: Dean
Gender: Male
Age: 19
You have tried logging in 1 times
这很好,但当我关闭代码并重新运行它时,它会再次打印相同的内容。显然,我只是在该实例中更改了self.login\u尝试
(即,当我运行代码时),但当我关闭代码并重新运行时,它会返回到0
我的问题是,为什么会这样
我的意思是很明显,每次我运行程序时,self.login\u attempts
都被设置为0
,但这对我来说似乎有些奇怪
是否有办法修改代码,以便在每次重新运行self.login\u尝试时
会自动递增,而无需多次调用用户.increment\u login\u尝试()?换句话说,是否有一种真正的方法可以通过重新运行代码来更改self.login\u truments=0的值?当您更改类的现有实例的属性时,更改仅限于此时内存中的内容。如果您想使其持久化,那么下次运行程序时,您需要将数据保存在文件或数据库之类的位置
您可以使用Python内置的pickle
模块将其保存到文件中,这样做相当容易。(有关更多详细信息,请参见我对问题的回答。)
在类中使用它的一种方法是创建一个users
字典,将用户名映射到user
类的实例。在下面的示例中,用户的名字和姓氏连接在一起,形成字典的键
class User():
... # Your class.
if __name__ == '__main__':
# Example of creating, reading, and updating a persistent users dictionary.
from pathlib import Path
import pickle
db_filepath = Path('user_database.pkl')
if not db_filepath.exists():
# Create database and add one user for testing.
users = {}
user = User("Sean", "Dean", "Male", 19)
users[', '.join((user.last_name, user.first_name))] = user
with open(db_filepath, 'wb') as outp:
pickle.dump(users, outp, -1)
print('database created with one user:')
user.describe_user()
if db_filepath.exists():
# Read existing database.
with open(db_filepath, 'rb') as inp:
users = pickle.load(inp)
print('Users in existing database:')
for user in users.values():
user.describe_user()
print()
user = users['Dean, Sean'] # Assume user exists.
if user.login_attempts > 3: # Reset if more than 3.
print('Resetting Sean Dean\'s login attempts.')
user.reset_login_attempts()
print('Incrementing Sean Dean\'s login attempts.')
user.increment_login_attempts()
# Update the database file.
with open(db_filepath, 'wb') as outp:
pickle.dump(users, outp, -1)
当您更改一个类的现有实例的属性时,更改仅限于此时内存中的内容。如果您想使其持久化,那么下次运行程序时,您需要将数据保存在文件或数据库之类的位置
您可以使用Python内置的pickle
模块将其保存到文件中,这样做相当容易。(有关更多详细信息,请参见我对问题的回答。)
在类中使用它的一种方法是创建一个users
字典,将用户名映射到user
类的实例。在下面的示例中,用户的名字和姓氏连接在一起,形成字典的键
class User():
... # Your class.
if __name__ == '__main__':
# Example of creating, reading, and updating a persistent users dictionary.
from pathlib import Path
import pickle
db_filepath = Path('user_database.pkl')
if not db_filepath.exists():
# Create database and add one user for testing.
users = {}
user = User("Sean", "Dean", "Male", 19)
users[', '.join((user.last_name, user.first_name))] = user
with open(db_filepath, 'wb') as outp:
pickle.dump(users, outp, -1)
print('database created with one user:')
user.describe_user()
if db_filepath.exists():
# Read existing database.
with open(db_filepath, 'rb') as inp:
users = pickle.load(inp)
print('Users in existing database:')
for user in users.values():
user.describe_user()
print()
user = users['Dean, Sean'] # Assume user exists.
if user.login_attempts > 3: # Reset if more than 3.
print('Resetting Sean Dean\'s login attempts.')
user.reset_login_attempts()
print('Incrementing Sean Dean\'s login attempts.')
user.increment_login_attempts()
# Update the database file.
with open(db_filepath, 'wb') as outp:
pickle.dump(users, outp, -1)
“这很好,但当我关闭代码并重新运行时,它会再次打印相同的内容。因此,显然,我只在该实例中更改self.login_尝试(即,当我运行代码时),但当我关闭代码并重新运行时,它会返回到0”当然。一旦进程终止,所有内容都将被回收。你的一切都在记忆中,但实际上你并没有保留任何东西。这是程序工作原理的一个非常基本的方面。如果您想保存用户登录尝试,请维护数据库”,这很好,但当我关闭代码并重新运行它时,它会再次打印相同的内容。因此,显然,我正在更改self.login\u仅在该实例中尝试(即,当我运行代码时)但是当我关闭代码并重新运行时,它当然会返回到0”。一旦进程终止,所有内容都将被回收。你的一切都在记忆中,但实际上你并没有保留任何东西。这是程序工作原理的一个基本方面。如果要保存用户登录计划,请维护数据库