met*_*ers 2 python pandas jupyter-notebook
当我在 jupyter 笔记本中调用不带圆括号的函数描述时,结果是不同的,但是我希望在不带括号的调用中出现错误消息。在搜索时,我只找到了有关的文章describe(),但没有找到有关的文章describe。我觉得问这个问题就像个傻瓜,因为我确信这很简单,但我还不明白。
代码如下所示:
file_path = '../input/data.csv'
data = pd.read_csv(file_path)
data.describe #instead of data.describe()
Run Code Online (Sandbox Code Playgroud)
两个结果如下所示:
.describe是绑定方法。它绑定到您的数据框,并且绑定方法的表示repr()包括它所绑定的任何内容的输出。
您可以在输出的开头看到这一点:
<bound method NDFrame.describe of ...>
Run Code Online (Sandbox Code Playgroud)
其余的字符串与生成的字符串相同repr(data)。
请注意,Python 交互式解释器始终回显最后生成的表达式的表示(除非它生成None)。data.describe生成绑定方法,data.describe()生成该方法设计生成的任何内容。
您可以为任何绑定方法创建相同类型的输出:
>>> class Foo:
... def __repr__(self):
... return "[This is an instance of the Foo class]"
... def bar(self):
... return "This is what Foo().bar() produces"
...
>>> Foo()
[This is an instance of the Foo class]
>>> Foo().bar
<bound method Foo.bar of [This is an instance of the Foo class]>
>>> Foo().bar()
"This is what Foo().bar() produces"
Run Code Online (Sandbox Code Playgroud)
请注意,它Foo()有一个自定义__repr__方法,调用该方法来生成实例的表示形式。
对于您实际未调用的数据帧上的任何方法,您可以看到相同类型的输出(整个数据帧的表示),例如data.sum、data.query、data.pivot或data.__repr__。
绑定方法是 Python 在调用实例时将实例作为第一个参数传递的过程的一部分,该参数通常名为self。它基本上是一个代理对象,引用原始函数 ( data.describe.__func__) 和在所有其他参数 ( ) 之前传递的实例data.describe.__self__。有关绑定如何工作的详细信息,请参阅描述符 HOWTO 。
如果您想将__repr__绑定方法的实现表示为 Python 代码,则为:
def __repr__(self):
return f"<bound method {self.__func__.__qualname__} of {self.__self__!r}>"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2797 次 |
| 最近记录: |