I have a very basic question; if this is a duplicate please link me to it as I wasn’t sure what to search!
I’d like the ask what the difference between object.method() and method(object) is. For instance, when I was defining a stack class, I noticed that peek(stack) returned name error while stack.peek() worked fine. Why is this so? Please forgive me is this is a duplicate, will remove this question if so!
1 Answer 1
Assuming this class definition:
# foo.py
class Stack(object):
def peek(self):
return 42
The peek function, being declared in the class statement block, becomes an attribute of the Stack class and not a module global of the foo module, so you cannot access it directly - you need to look it up on Stack, ie:
# foo.py continued
obj = Stack()
try:
peek(obj)
except NameError:
print("peek is not a module-level function")
Stack.peek(obj)
# or more simply
obj.peek()