I am seeking for a confirmation if my thinking is correct in terms of Python method vs function:
A method is a part of a class.
A function is defined outside of a class.
so e.g.
class FooBar(object):
def __init__(self):
pass
def foo(self):
pass
def bar():
pass
if __name__ == '__main__':
fb = FooBar()
I understand def foo defines method and def bar defines function. Am I correct?
Yes. To be clear, methods are functions, they are simply attached to the class, and when that function is called from an instance it gets that instance passed implicitly as the first argument automagically*. It doesn't actually matter where that function is defined. Consider:
class FooBar:
def __init__(self, n):
self.n = n
def foo(self):
return '|'.join(self.n*['foo'])
fb = FooBar(2)
print(fb.foo())
def bar(self):
return '*'.join(self.n*['bar'])
print(bar(fb))
FooBar.bar = bar
print(fb.bar())
*I highly recommend reading the descriptor HOWTO. Spoiler alert, Functions are descriptors. This is how Python magically passes instances to methods (that is, all function objects are descriptors who's __get__ method passes the instance as the first argument to the function itself when accessed by an instance on a class!. The HOWTO shows Python implementations of all of these things, including how you could implement property in pure Python!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With