Python Forum

Full Version: Why is this pointing to the objects
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all.

I dont quite understand why these two different objects are pointing to the list object? Could anyone please help me understand this?
class A:

    l = [1]

    def __init__(self):
        pass

a = A()
a1 = A()

print(id(a.l))
print(id(a1.l))
Output:
140465203999880 140465203999880
Many thanks
There is really nothing to understand here: variables stored in the class object A, such as A.l are shared by all the instances of that class.
(Apr-09-2019, 07:44 PM)Gribouillis Wrote: [ -> ]There is really nothing to understand here: variables stored in the class object A, such as A.l are shared by all the instances of that class.

Sure - that exactly is the question, why? When I create two different object of type class A. Shouldn't that create two different list? Or is this some sort optimization i've overlooked all this time?
Your looking for instance variables.
class A:
 
#     l = [1]
 
    def __init__(self):
        self.l = [1]
 
a = A()
a1 = A()
 
print(id(a.l))
print(id(a1.l))
Output:
2413810246280 2413810246344
This really is interesting. My illusion was that anything within the class block would be instance variable. It appears from what your demonstrating is that unless you but anything within the constructor it remains as class variable. Which meant there's only one instance of the list, since it was defined/declared outside the constructor.
class A:
 
    l = [1]
 
    def __init__(self):
        self.l = [1]

a = A()
a1 = A()
 
print(id(a.l), id(A.l))
print(id(a1.l), id(A.l))

A.l.append('Class')
a.l.append('instance a')
a1.l.append('instance a1')
print(A.l, a.l, a1.l)
Output:
2924812853960 2924812853896 2924816376776 2924812853896 [1, 'Class'] [1, 'instance a'] [1, 'instance a1']
That's brilliant. I feeling very stupid to have not tried that before. And thinking of performance first.
But many thanks :)