-2

I am a begineer in python and sorry if it sound like a newbie question, but i am really confused about the differences between the two. Can someone please explain this with examples, it would be really helpful. Thanks in advance.

  • A bound method is an instance method which has been bound to the instance. – juanpa.arrivillaga Dec 02 '19 at 18:27
  • Does this answer your question? [Class method differences in Python: bound, unbound and static](https://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static) – Sam Mason Dec 02 '19 at 18:53

1 Answers1

1

By default, all methods you create are instance methods. For instance, here distance_to_origin is an instance method of class Point:

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

  def distance_to_origin(self):
    return (self.x**2 + self.y**2)**0.5

Point.distance_to_origin is just a function that takes one argument and does some computation on it.

>>> Point.distance_to_origin
<function Point.distance_to_origin at 0x7f2cd4610a60>

As juanpa.arrivillaga said in the comment, a bound method is an instance method bound to an instance.

>>> p = Point(3, 4)
>>> p.distance_to_origin
<bound method Point.distance_to_origin of <__main__.Point object at 0x7f2cd3f5aba8>>
>>> p.distance_to_origin()
5.0

You can think of it as a partially applied function, where the object to which the method was bound will be assigned to self.

>>> f = p.distance_to_origin
>>> f()
5.0

Apart from instance methods, there are also class methods and static methods. Class methods act on classes, and static methods act neither on classes nor on instances of classes.

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

  @classmethod
  def from_polar(cls, r, theta):
    x = r * cos(theta)
    y = r * sin(theta)
    return cls(x, y)

  @staticmethod
  def from_polar(r, theta):
    x = r * cos(theta)
    y = r * sin(theta)
    return Point(x, y)

You can read about them here: https://www.geeksforgeeks.org/class-method-vs-static-method-python/

decorator-factory
  • 2,733
  • 13
  • 25