1

I wrote codes as follow:

class a:
    e = [1,2,3]
    def __init__(self):
        self.name = 'Adam'

b = a()
c = a()
if b.e is c.e:
    print('they are same')

the outcome is:

they are same

It shows that b.e and c.e point to the same object. And if I use id(a), it would return me an address in memory, showing that a has been created as an object.

When I want to creat an instance like b=a(), codes in the __init__() are excuted. But I am confused that when and how e (or other members like other methods) is bound to the instance? (Actually in __init__() there is no lines like "let's bind e to this instance")

Eason Wang
  • 29
  • 1
  • 6
  • 1
    Because e is "bound to" the class, not the instance. Everything that is "bound to" a class is also available in every instance on that class. – luk2302 May 03 '22 at 06:06
  • class variables are created once for all objects so there ids are same. To check this you can simply change `b.e.append(3)` and check by printing `print(c.e)` – Deepak Tripathi May 03 '22 at 06:07

3 Answers3

1

e in your case is a class variable because it is declared directly under your class and not in the init, this means that it is bound to the class and not to the instance of your object.

baskettaz
  • 741
  • 3
  • 12
0

e is a class variable attached to your class a

The usual way you should be accessing an instance variable is

class a:
  def __init__(self):
    self.e=[1,2,3]
    self.name = 'Adam'

Back into your example, add this line

a.e=[4,5,6]

and check how b.e and c.e have changed...

Daniel Exxxe
  • 59
  • 1
  • 7
0

because it's declared as a class variable, not an instance variable.

Class variable: Once copy of variable is shared between all instances.

Instance variable: Each instance has its own value and not shared between different instances of same class.

the following code will give you false.

class a:
    def __init__(self):
        self.name = 'Adam'
        self.e = [1,2,3]

b = a()
c = a()
if b.e is c.e:
    print('they are same')
else:
    print("not the same")

output

"not the same"
huzzzus
  • 172
  • 10