命令与需要 () 与不需要的区别是什么? [英] What distinguishes a command from needing () vs not?
问题描述
我最近花了很长时间调试一段代码,才意识到问题是我没有在命令后包含 ().哪些命令需要 () 而哪些不需要?
I recently spent way too long debugging a piece of code, only to realize that the issue was I did not include a () after a command. What is the logic behind which commands require a () and which do not?
例如:
import pandas as pd
col1=['a','b','c','d','e']
col2=[1,2,3,4,5]
df=pd.DataFrame(list(zip(col1,col2)),columns=['col1','col2'])
df.columns
按预期返回 Index(['col1', 'col2'], dtype='object')
.如果我们使用 .columns()
我们会得到一个错误.
Returns Index(['col1', 'col2'], dtype='object')
as expected. If we use .columns()
we get an error.
其他命令则相反:
df.isna()
返回:
col1 col2
0 False False
1 False False
2 False False
3 False False
4 False False
但是 df.isna
返回:
<bound method DataFrame.isna of col1 col2
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5>
虽然不会抛出错误,但显然不是我们想要的.
Which, while not throwing an error, is clearly not what we're looking for.
哪些命令使用 () 哪些不使用的逻辑是什么?
我在这里以 Pandas 为例,但我认为这更普遍地与 python 相关.
I use pandas as an example here, but I think this is relevant to python more generally.
推荐答案
因为函数的参数需要括号,而变量不需要,这就是为什么它是list.append(
但它是 list.items
.
Because functions need parenthesis for their arguments, while variables do not, that's why it's list.append(<item>)
but it's list.items
.
如果你调用一个没有括号的函数,比如 list.append
返回的是函数的描述,不是函数的描述做什么,但是描述它是什么.
If you call a function without the parenthesis like list.append
what returns is a description of the function, not a description of what the function does, but a description of what it is.
对于类,调用带括号的类会启动该类的对象,而调用带括号的类则指向类>itself,这意味着如果你要执行 print(SomeClass)
你会得到
这是一个对它是什么的描述,如果你调用一个没有括号的函数,你会得到同样的响应.
As for classes, a call to a class with parenthesis initiates an object of that class, while a call to a class without the parenthesis point to the class itself, which means that if you were to execute print(SomeClass)
you'd get <class '__main__.SomeClass'>
which is a description of what it is, the same kind of response you'd get if you were to call a function without parenthesis.
这篇关于命令与需要 () 与不需要的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!