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!

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.