Python Forum
Why is this pointing to the objects
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why is this pointing to the objects
#1
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
Reply
#2
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.
Reply
#3
(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?
Reply
#4
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
Reply
#5
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.
Reply
#6
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']
Reply
#7
That's brilliant. I feeling very stupid to have not tried that before. And thinking of performance first.
But many thanks :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sorting Elements via parameters pointing to those elements. rpalmer 3 2,604 Feb-10-2021, 04:53 PM
Last Post: rpalmer
  Installing Python and pointing it to required libraries hooiberg 2 4,321 May-13-2019, 05:55 PM
Last Post: ebolisa
  What are ways of pointing cross-compiled origin source line for python? wyvogew 2 2,830 Feb-02-2019, 03:16 PM
Last Post: wyvogew

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020