gpt4 book ai didi

Python 类变量不更新

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:11 24 4
gpt4 key购买 nike

我有一个类正在接受一个 Id 并尝试更新变量 current_account 但是当我打印出 current_account 的详细信息时它没有更新。

有人对此有任何想法吗? Python 的新手,所以可能会做一些我看不到的蠢事。

class UserData:
def __init__(self, db_conn=None):
if None == db_conn:
raise Exception("DB Connection Required.")

self.db = db_conn
self.set_my_account()
self.set_accounts()
self.set_current_account()

def set_current_account(self, account_id=None):
print account_id
if None == account_id:
self.current_account = self.my_account
else:
if len(self.accounts) > 0:
for account in self.accounts:
if account['_id'] == account_id:
self.current_account = account
print self.current_account['_id']
else:
raise Exception("No accounts available.")

假设 set_my_account() 获取帐户数据字典,set_accounts() 获取帐户数据字典列表。

所以当我执行以下操作时:

user_data = UserData(db_conn=db_conn)
user_data.set_current_account(account_id=account_id)

其中 db_conn 是有效的数据库连接,account_id 是有效的帐户 ID。

我从以上两行中得到以下内容。

None
518a310356c02c0756764b4e
512754cfc1f3d16c25c350b7

因此 None 值来自类的声明,接下来的两个值来自对 set_current_account() 的调用。第一个 id 值是我要设置的值。第二个 id 值是已经从类 __init__() 方法中设置的值。

最佳答案

有很多冗余和非 Pythonic 结构。我清理了代码以帮助我理解您想要做什么。

class UserData(object):
def __init__(self, db_conn):
self.db = db_conn
self.set_my_account()
self.set_accounts()
self.set_current_account()

def set_current_account(self, account_id=None):
print account_id
if account_id is None:
self.current_account = self.my_account
else:
if not self.accounts:
raise Exception("No accounts available.")

for account in self.accounts:
if account['_id'] == account_id:
self.current_account = account
print self.current_account['_id']

user_data = UserData(db_conn)
user_data.set_current_account(account_id)

当没有显式参数的调用无效时,您使用了默认参数 (db_conn=None)。是的,您现在可以调用 __init__(None),但您也可以调用 __init__('Nalum');你无法防范一切。

通过移动“无帐户”异常(exception),阻止快速失败,您可以节省一级缩进。

调用 UserData(db_conn=db_conn) 有效但不必要地重复。

不幸的是,我仍然无法弄清楚你想要完成什么,这可能是最大的缺陷。变量名对于帮助读者(可能是 future 的你)理解代码非常重要。 current_accountmy_accountaccount_idcurrent_account['_id'] 如此模糊你真正应该考虑更多的意图独特的、信息丰富的名称。

关于Python 类变量不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16463809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com