【问题标题】:Creating attribute names from dict keys using var()使用 var() 从 dict 键创建属性名称
【发布时间】:2012-08-07 13:29:52
【问题描述】:

我正在使用vars()“即时”创建一些对象变量。这似乎不是最干净的操作。但是,如果不手动定义它们,我怎么能生成对象的属性名称(在这种情况下,dict 相对较短,但这只是一些测试数据)。我知道here 描述的这种做法带来的问题。

class DerivedProf(Prof):
    def __init__(self,profiel, TAG, code_DB):
       Prof.__init__(self, profiel, TAG)
       self.CountCodes(self.attr, code_DB)

def CountCodes(self, attr, code_DB):
    count  = 0 
    for key, value in code_DB.iteritems():
        if value[0].lower() == 'true':
            for i,p in enumerate(attr):
                if int(attr[i].code2) == value[1]:
                    count += 1
                else:
                    continue
            vars(self)[key] = count 

code_DB = {'code_72': ['true',72],
          'code_74': ['true',74],
          'code_76': ['true',76],
          'code_88': ['true',88]}

【问题讨论】:

    标签: python object attributes


    【解决方案1】:

    也许您正在寻找setattrgetattr。你可以先setattr(self, key, count),然后再getattr(self, key)

    【讨论】:

    • 这正是我想要的!谢谢老兄。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2018-08-04
    • 2013-04-22
    • 1970-01-01
    • 2019-08-13
    • 2013-08-21
    相关资源
    最近更新 更多