简体   繁体   中英

Instance methods in Python

In C++, 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. Is it the same case with Python or different copies of methods exists for each instance of the class ?

Yes - only one copy of the method exist in memory:

Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
...     def test():
...         return 1
...
>>> a = A()
>>> b = A()
>>> id(a.test)
140213081597896
>>> id(b.test)
140213081597896

Yes for the class methods and instance methods the functions are located in the same memory slot for all instances.

But you won't be able to override that method and impact other instances, by overriding you simply add new entry to the instance dict attribute ( see class attribute lookup rule? for more context on the lookup).

>>> class A():
...   def x():pass
... 
>>> s = A()
>>> d = A()
>>> id(s.x)
4501360304
>>> id(d.x)
4501360304

Let's find an answer together, with a simple test:

class C:
    def method(self):
        print('I am method')

c1 = C()
c2 = C()

print(id(c1.method))  # id returns the address 
>>> 140161083662600

print(id(c2.method))
>>> 140161083662600

Here id(obj):

Return the identity of an object.

This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM