Search code examples
pythoninstance-methods

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 ?


Solution

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