leob leob - 1 year ago 75
Python Question

In Python how can I add each new instance of a class to a list upon initialization?

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):


def __init__(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?

Answer Source

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>]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download