0

I am learning about method binding and am trying to understand, how the interpretor makes the connection between an object of a specific type and it's instance methods. Suppose I have written the following code:

class Point:
    def __init__(self, x,y):
        self._x=x
        self._y=y

    def draw(self):
        print(self._x, self._y)

p1=Point(1,2)
p1.draw() 

I was told that draw is an instance method. If that's the case, then where is draw stored? I understand that attributes are stored in a dictionary whose keys are the attribute names and the values are the values of the attributes, but I'm struggling to make the connection between the instance methods and the object itself. Are they stored where the class is stored in memory or are they stored with the object(p1)? How?

Teererai Marange
  • 2,044
  • 4
  • 32
  • 50
  • If you want your question to be fully answered I'm afraid that you should read the source code and find out the answer by yourself, If you're familiar with C (presuming that you're talking about the Cpython implementation tho). – Mazdak Oct 14 '18 at 07:13

1 Answers1

1

You can say that methods are also attributes in a class and they are basically functions bound to a class. You can see them with Class.__dict__.

When you use Point.__dict__, it returns a mapping like this:

mappingproxy({'__module__': '__main__',
              '__init__': <function __main__.Point.__init__(self, x, y)>,
              'draw': <function __main__.Point.draw(self)>,
              '__dict__': <attribute '__dict__' of 'Point' objects>,
              '__weakref__': <attribute '__weakref__' of 'Point' objects>,
              '__doc__': None})

You can see that draw is a function object inside the class Point and self is the instance.

You can also call those methods with this syntax since draw belongs to the class Point

Point.draw(p1)

which is the same as

p1.draw()
gunesevitan
  • 882
  • 10
  • 25