I want to get all the instances created for a class. Is there any way to get the instances without importing any module ?
I tried this way to append self in a class attribute.
class A(object):
instances = []
def __init__(self, foo):
self.foo = foo
A.instances.append(self)
foo = A("hi")
bar = A("Hey")
star = A("Hero")
for instance in A.instances:
print("Ins is ",instance)
Output
<__main__.A object at 0x148b8b6e0780>,
<__main__.A object at 0x148b8b6e0780>,
<__main__.A object at 0x148b8b6e0780>
I expect it to print foo,bar,star. Is there any way to get it in class without any module?
CodePudding user response:
Use this snippet:
for instance in A.instances:
print("Ins is ", (instance.__dict__).get("foo"))
Output:
Ins is hi
Ins is Hey
Ins is Hero
Or:
for instance in A.instances:
print("Ins is ", instance.__dict__)
Output:
Ins is {'foo': 'hi'}
Ins is {'foo': 'Hey'}
Ins is {'foo': 'Hero'}
To print an object, you can turn it into a dictionary. In this case, these values will be printable.
This method is usually used to convert objects to a dictionary and then to the JSON type, which is widely used to exchange information.
CodePudding user response:
you could do the following, if I got you right :
Proposal
tmp = globals().copy()
print(tmp)
for k,v in tmp.items():
if isinstance(v, A):
print(k)
You must copy the global variable dictionary, because otherwise i will be changed with the first instantiation in the for-loop:
Result:
foo
bar
star
CodePudding user response:
There is no way to define such behavior in a class, because the class assigns a value to a variable after instantiation. There is no way to get the name of the variable during class instantiation, because the variable does not exist yet
