简体   繁体   English

方法和属性python之间的区别?

[英]difference between method and attribute python?

I'm probably using the wrong terminology here, but I'm looking for an explanation on the difference between a function called on an object, ie method, and then an attribute of the object itself. 我可能在这里使用了错误的术语,但是我正在寻找一个关于在对象上调用的函数(即方法)与对象本身的属性之间的区别的解释。

Take the following df: 取以下df:

df = pd.DataFrame({'a':[4, 5, 6, 7],
                   'b':[3, 2, 5, 4]})

You can call the sum() method/function on df, and you can call the columns attribute on df. 您可以在df上调用sum()方法/函数,并且可以在df上调用columns属性。 I may be getting confused between chaining a method vs. calling an attribute using . 在链接方法与使用调用属性之间,我可能会感到困惑. .

df.sum()
df.columns

They're the same. 他们是一样的。 Methods are pretty much just attributes that happen to be of type function or any other runnable type. 方法几乎只是碰巧function类型或任何其他可运行类型的属性。 If you do 如果你这样做

>>> f = df.sum

it'll work perfectly fine. 它会很好地工作。 If you then check the type, you'll see 如果您随后检查类型,则会看到

>>> type(f)
<type 'instancemethod'>

or something similar along those lines. 或类似的东西。 You can call any object of that type as a function, which is why you can do df.sum() : first it's finding the attribute of df that happens to be a function, and then it's calling it. 您可以将该类型的任何对象调用为函数,这就是为什么可以执行df.sum() :首先,它找到恰好是函数的df属性,然后对其进行调用。

You can't "call" the df.columns part of a DataFrame. 您不能“调用” df.columns部分。 It's a data part of a DataFrame, and you "reference" it. 它是DataFrame的数据部分,您可以“引用”它。 df.sum() you can "call", because sum() is an executable part of the DataFrame. df.sum()您可以“调用”,因为sum()是DataFrame的可执行部分。

The tricky bit (and I'm trying to avoid ambiguous language here) is that a DataFrame has both of those kinds of things: data parts and code parts. 棘手的一点是(我试图在这里避免使用歧义的语言)是DataFrame 具有以下两种类型的东西:数据部分和代码部分。 They can both change, be inherited, etc. But they're really different: You can't "call" columns, and you (generally) don't reference sum() . 它们都可以更改,被继承等。但是它们确实不同:您不能“调用”列,并且(通常)您不引用sum()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM