在Python中的方法,函数或运算符之后使用和不使用()有什么区别?

时间:2019-09-23 07:47:26

标签: python pandas

例如

import pandas as pd
weather = pd.read_csv(r'D:\weather.csv')
weather.count
weather.count()

天气是一个具有多列和多行的数据框 那么,当请求weather.count和weather.count()有什么区别?

2 个答案:

答案 0 :(得分:2)

这取决于。总的来说,这个问题与大熊猫无关。答案与Python的设计方式有关。

在这种情况下,.count是一种方法。特别是一种pandas.DataFrame的方法,它将确认它:

df = pd.DataFrame({'a': []})
print(df.count)

输出

<bound method DataFrame.count of Empty DataFrame
Columns: [a]
Index: []>

添加()将调用此方法:

print(df.count())

输出

a    0
dtype: int64


但是,并非总是如此。 .count可能是不可调用的属性(例如,字符串,整数等)或属性。

在这种情况下,它是不可调用的属性:

class Foo:
    def __init__(self, c):
        self.count = c

obj = Foo(42)
print(obj.count)

将输出

42

在这种情况下添加()将引发异常,因为调用整数没有意义:

print(obj.count())
TypeError: 'int' object is not callable

答案 1 :(得分:-2)

双括号与方法调用有关。

如果声明这样的函数,该函数将两个数字相加:

def sum(a:int, b:int)->int:
    return a+b

然后您可以使用:sum(1,2)调用函数。

不带括号的函数在不需要调用该函数时使用,而是需要将该函数的引用传递给另一个方法。

例如,传递对该函数的引用可能对多线程管理很有用:

from multiprocessing import Process
t = Process(target=my_long_running_function)

请查看@roippi回复以获取更多信息: https://stackoverflow.com/a/21786508/9361998