首页 > 解决方案 > Reason for parentheses after read, truncate and close commands?

问题描述

Could someone explain to me what the parentheses after the .read(), .truncate()and .close() commands are doing?

I'm confused by why they're empty and why it isn't written as: read(filename), truncate(filename), and close(filename) rather than filename.read(), filename.truncate(), and filename.close()?

But open is written as open(filename) and not filename.open()

标签: python

解决方案


这些括号()用于实际调用某个函数,而不仅仅是引用它。

考虑例如:

def func():
    return "I am being called!"


print(func)
# <function func at 0x7f41f59a6b70>

print(func())
# I am being called!

关于:func(x)x.func()语法,这是一个设计/风格的选择。

第一种语法与过程设计/风格相关联,而第二种语法与明确的面向对象设计/风格相关联。

Python(以及许多其他通用语言)两者都支持。

何时func设计为:

def func(x):
    ...

您将使用程序样式。

何时func设计为:

class MyX(object):
    def func(self):
        ...

您将使用面向对象的样式。请注意,这需要x是类型MyX(或其子类)。

更多信息可在 Python 教程中找到,例如这里

最后一点:在某些编程语言(尤其是Dnim)中有统一函数调用语法的概念,它基本上允许您编写函数,然后使用您喜欢的任何语法(过程或面向对象)调用它。


推荐阅读