1

I am learning about classes in python right now. My apologies if my language is a little sloppy, but I'm still trying to understand exactly how classes work.

While working through some projects of my own, I often find myself wanting to add an object, upon initialization, to a list so I can keep a track of all the objects I have made of that type. I have been trying to do this in the following way:

class My_Class(object):

    Object_List=[]

    def __init__(self):
        Object_List.append(self)

However, from what I can tell, the "_ _init _ _" suite doesn't have object list in it's namespace. If this is correct, it would seem to make sense, because functions have their own namespace. However the issue then is the above code doesn't work. I don't seem to be able to add my objects to a globally defined list.

Can anyone suggest another way I could accomplish the same thing, and end up with a list of all the My_Class objects I have created?

leob
  • 141
  • 2
  • 7
  • 1
    Try `self.Object_List.append(self)`. `Object_List` is an attribute of the class and in this case you need to access it through the class instance. – Tom Dalton Nov 29 '16 at 08:44
  • @TomDalton Wouldn't that make `Object_List` an instance variable? – Robin Koch Nov 29 '16 at 08:53
  • If you hadn't already defined it at the class level (via `Object_List=[]`, then yes. However, because you *have* defined it at the class level, and because the `append` isn't an assignment operation (even though it looks like a 'write' it's really a variable lookup followed by a method call), then `self.Object_List` will find the class-level variable and modify it. If you had a class level variable that wasn't a list, e.g. a string, then doing `self.my_string = 'foo', would create a new instance-level variable, which would shadow the class-level variable of the same name. – Tom Dalton Nov 29 '16 at 09:01
  • Also see some of the answers on http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes that go into a bit more detail. – Tom Dalton Nov 29 '16 at 09:02

1 Answers1

3

Try the following:

>>> class A():
...     my_list = []
...     def __init__(self):
...         A.my_list.append(self)
...
>>>
>>> a = A()
>>> A.my_list
[<__main__.A instance at 0x0000000002563548>]
>>> b = A()
>>> A.my_list
[<__main__.A instance at 0x0000000002563548>, <__main__.A instance at 0x00000000025FB408>]
ettanany
  • 19,038
  • 9
  • 47
  • 63