Is putting objects in a list (in python) just like putting class object in ArrayList<object>
??
I tried this code
class foo():
def __init__(self):
self.name = "frank"
self.id = 007
obj1 = foo()
obj2 = foo()
element_list = []
element_list.append(obj1)
element_list.append(obj2)
for element in element_list:
print(type(element))
print(element.name)
The object type turned out to be <type 'instance'>
. But then the object correctly printed the variable assigned.
How does python identify the type of these instances? Even if it is getting an instance object, how is it able to map the class?
type()
does not work correctly for instances of old-style classes (Python 2 classes that do not inherit fromobject
). Python looks at the.__class__
attribute instead:For instances of new-style classes (so those classes that do inherit from
object
),type()
simply returns the__class__
attribute directly.Not that it matters here; all you are really doing is looking at attributes, stored directly on the instance itself. Those are stored in the
__dict__
attribute of each instance:Method lookups (as well as any other attribute that is defined on the class or its bases), do require that Python looks at the class:
For that the
__class__
attribute is used here.