1

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 ?

1

3 Answers 3

1

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

First thank you for your answer. But can you also tell why when I use print(id(c1.method)) and print(id(C.method)) it gives different results ? Whats happening here ?
Ah, there is a beauty of Python awaiting you :) Internally Python uses the so-called descriptors mechanism to make Class properties, classmethods, staticmethods and... usual class instance aka objects' methods. It is a long topic to describe in 500 characters - but here is a good place to start: docs.python.org/3.7/howto/descriptor.html In short - a function defined in class body becomes a method of an object by binding. A single binding is used (referred by) all instances of a class.
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.