1

1- is it true? all the objects of a particular class have their own data members but share the member functions, for which only one copy in the memory exists?

2- and why the address of init in this code is similar:

class c:
    def __init__(self,color):
        print (f"id of self in __init__ on class is {id(self)}")
         
    def test(self):
        print("hello")
    print (f"id of __init__ on class is {id(__init__)}")



a=c("red")
print(id(a.__init__))
print(id(a.test))
b=c("green")
b.test()
print(id(b.__init__))
print(id(b.test))

Output:
id of __init__ on class is 1672033309600
id of self in __init__ on class is 1672033251232
**1672028411200 
1672028411200**
id of self in __init__ on class is 1672033249696
hello
**1672028411200
1672028411200**
mim
  • 11
  • 2

1 Answers1

3
  1. Yes, all instances share the same code for a method. When you reference the method through a specific instance, a bound method object is created; it contains a reference to the method and the instance. When this bound method is called, it then calls the method function with the instance inserted as the first argument.

  2. When you reference a method, a new bound method object is created. Unless you save the reference in a variable, the object will be garbage collected immediately. Referring to another method will create another bound method object, and it can use the same address.

Change your code to

init = a.__init__
test = a.test
print(id(init))
print(id(test))

and you'll get different IDs. Assigning the methods to variables keeps the memory from being reused.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • do you have response for my first question? – mim Mar 28 '21 at 07:11
  • thanks a lot. can you introduce me a good reference about this subject that learn bounding methods and related topic about that? – mim Mar 28 '21 at 08:40
  • Google "python bound method": https://www.geeksforgeeks.org/bound-unbound-and-static-methods-in-python/ https://www.geeksforgeeks.org/bound-methods-python/ – Barmar Mar 28 '21 at 21:49