0

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!

Zoe - Save the data dump
28.4k22 gold badges130 silver badges163 bronze badges
asked Sep 14, 2018 at 9:29

1 Answer 1

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()
answered Sep 14, 2018 at 11:38
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.