【问题标题】:Printing each objects of class Python打印 Python 类的每个对象
【发布时间】:2021-08-19 20:59:15
【问题描述】:

下面的类函数为Account1Account2 创建一个对象。如何在 for 循环之外打印不同的对象值?

accounts= {'Account1': OrderedDict([('AccountName', 'Account1'), ('APIkey', 'xczccdfc'), ('APIsecret', 'sdasdadsadcd')]), 'Account2': OrderedDict([('AccountName', 'Account2'), ('APIkey', 'asdasdadcrf'), ('APIsecret', 'asdase346')])}

class Dummy:
    pass

for account in accounts:
    '''
    Create a dummy function  to update APIkey and APIsecret, 
    here then reference it as infos.key or infos.secret in stats.auth()
    '''
    dummy = Dummy()
    dummy.key = accounts[account]["APIkey"]
    dummy.secret = accounts[account]["APIsecret"]
    
print(Account1.key)
print(Account2.key)

【问题讨论】:

  • dummy.keysdummy.secret 会被覆盖吗?
  • 不——你看到我的回答了吗?它将在类Dummy 的每个实例下设置它们

标签: python-3.x class dictionary for-loop object


【解决方案1】:

尽管过度使用/滥用 global 关键字通常不被接受/被认为是非 Pythonic,但您可以将 Dummy 类添加到全局变量的“字典”中。

通过使用您的属性初始化类,我能够获得您的预期行为:

class Dummy():
    def __init__(self, account_name):
        global accounts
        self.key = accounts[account_name]["APIkey"]
        self.secret = accounts[account_name]["APIsecret"]

for account in accounts.keys():
    globals()[account] = Dummy(account)

print(Account1.key)
print(Account2.key)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-06
    • 2016-01-10
    • 2021-08-02
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    相关资源
    最近更新 更多