[英]Difference between object.method() and method(object) in Python?
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. 我想问一下object.method()
和method(object)
之间的区别是什么。 For instance, when I was defining a stack class, I noticed that peek(stack)
returned name error while stack.peek()
worked fine. 例如,当我定义堆栈类时,我注意到peek(stack)
返回名称错误,而stack.peek()
工作。 Why is this so? 为什么会这样呢? Please forgive me is this is a duplicate, will remove this question if so! 请原谅我这是重复的,如果是的话将删除此问题!
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: 在class
语句块中声明的peek
函数成为Stack
类的属性,而不是foo
模块的全局模块,因此您无法直接访问它-您需要在Stack
上查找它,即:
# 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.