简体   繁体   English

Python中的object.method()和method(object)之间的区别?

[英]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.

相关问题 @ object.method在Python中做什么? - What does @object.method do in Python? Python 中的 module.function() 与 object.method()。 他们是一样的吗? - module.function() vs object.method() in Python. Are they the same? 将Object.method()的“ method()”部分作为参数传递 - Pass the “method()” portion of Object.method() as a parameter 打印(object.method)不打印预期的输出? - print(object.method) not printing expected output? 调用 object.method() 和 Class.method(object) 时,幕后发生了什么? - What is happening behind the scenes when calling object.method() and Class.method(object)? Django Wagtail:使用自己的object.method而不是重写object.get_context方法访问数据是否不好? - Django Wagtail: Is it bad practise access data using own object.method instead of rewriting object.get_context method? Python:使用 object 作为参数(例如方法(XXX)与以下语法:XXX.method())之间有区别吗? - Python: is there a difference between using an object as an argument e.g. method(XXX) vs. this syntax: XXX.method()? static 方法上的运行线程与使用 class object 运行之间的区别 - Difference between run thread on a static method vs running with class object __repr__方法中的self和object参数有什么区别? - What is the difference between self and object parameters in __repr__ method? 方法和属性python之间的区别? - difference between method and attribute python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM