【问题标题】:Access the attributes for an object stored in dictionary访问存储在字典中的对象的属性
【发布时间】:2018-03-16 01:31:00
【问题描述】:

我在类外的函数中为类的对象设置一些属性,并将对象存储在字典中。我看不到对象存储值的变化,检索的是默认初始化值。

class Logpkt():
    def __init__(self):
    self.a=0
    self.b=''
    self.c=''
    self.d=''
    self.e=''
    self.f=''
    self.g=''
    self.h=''
    self.i=''
    self.j=''
    self.k=''


def set_class(**kwargs):
    temp = Logpkt()
    print(kwargs)
    for attr in kwargs.keys():
        temp.attr=kwargs[attr]
        print temp.attr,kwargs[attr]
    return temp

obj={}
obj[1]=set_class(a=1,b=2)
obj[2]=set_class(c=1,d=2)
print obj[1].a
print obj[2].c

打印空白,这是默认值。超出范围后是否被垃圾清理器从内存中删除的对象?有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python python-2.7 object dictionary


    【解决方案1】:

    您需要使用setattr 喜欢:

    代码:

    def set_class(**kwargs):
        temp = Logpkt()
        for attr, value in kwargs.items():
            setattr(temp, attr, value)
        return temp
    

    测试代码:

    class Logpkt():
        def __init__(self):
            self.a = 0
    
            self.b = ''
            self.c = ''
            self.d = ''
            self.e = ''
            self.f = ''
            self.g = ''
            self.h = ''
            self.i = ''
            self.j = ''
            self.k = ''
    
    
    def set_class(**kwargs):
        temp = Logpkt()
        print(kwargs)
        for attr, value in kwargs.items():
            setattr(temp, attr, value)
        return temp
    
    
    obj = {}
    obj[1] = set_class(a=1, b=2)
    obj[2] = set_class(c=3, d=2)
    print(obj[1].a)
    print(obj[2].c)
    

    结果:

    {'a': 1, 'b': 2}
    {'c': 3, 'd': 2}
    1
    3
    

    【讨论】:

      猜你喜欢
      • 2014-03-04
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      相关资源
      最近更新 更多