instances

How to keep track of class instances?

戏子无情 提交于 2019-11-26 13:23:57
Toward the end of a program I'm looking to load a specific variable from all the instances of a class into a dictionary. For example: class Foo(): __init__(self): x = {} foo1 = Foo() foo2 = Foo() foo...etc. Let's say the number of instances will vary and I want the x dict from each instance of Foo() loaded into a new dict. How would I do that? The examples I've seen in SO assume one already has the list of instances. One way to keep track of instances is with a class variable: class A(object): instances = [] def __init__(self, foo): self.foo = foo A.instances.append(self) At the end of the

Why can't you add attributes to object in python? [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-11-26 06:36:55
问题 This question already has an answer here: Can't set attributes of object class 6 answers (Written in Python shell) >>> o = object() >>> o.test = 1 Traceback (most recent call last): File \"<pyshell#45>\", line 1, in <module> o.test = 1 AttributeError: \'object\' object has no attribute \'test\' >>> class test1: pass >>> t = test1() >>> t.test Traceback (most recent call last): File \"<pyshell#50>\", line 1, in <module> t.test AttributeError: test1 instance has no attribute \'test\' >>> t.test