python - 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()
解决方案
这些括号()
用于实际调用某个函数,而不仅仅是引用它。
考虑例如:
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 教程中找到,例如这里。
最后一点:在某些编程语言(尤其是D
和nim
)中有统一函数调用语法的概念,它基本上允许您编写函数,然后使用您喜欢的任何语法(过程或面向对象)调用它。
推荐阅读
- python - 如何从关联表中查询属性(SQLalchemy)
- apache-spark - 为多个租户触发具有条件过滤逻辑的作业
- c# - HttpWebRequest 获取“底层连接已关闭”
- python - 多处理,Python3,Windows:TypeError:无法腌制 _thread.lock 对象
- c - 将整数和字符串转换为十六进制字符串,并在 C 中以正确的字节序将它们放置在其他十六进制字符串之间
- mysql - 从 SELECT 语句返回的行更新值
- java - 如何限制用户选择 RecyclerView 列表中的 3 个选项
- sql-server-2000 - SQL Server 2000 中一列对应列的最大值
- push-notification - 适用于 iOS 和 Android 应用程序的 EWS 新电子邮件推送通知
- excel - VLOOKUP 使用 CONCATENATE 和范围之间的值