【问题标题】:Use a method or a function? [duplicate]使用方法还是函数? [复制]
【发布时间】:2014-07-24 12:09:03
【问题描述】:

我开始使用 Python,其中一些任务有一个方法和一个函数。假设是一个深拷贝

b = a.copy()

b = copy(a)
  1. 从性能的角度来看,为什么两者都有,哪个更好用?

  2. 如何在不查看文档的情况下快速确定某个任务是函数还是方法? hsplit 是一个函数,而不是一个方法。

【问题讨论】:

  • 我认为只有dict.copy() 方法。否则,copy 内置函数会对作为第一个参数传递的对象进行浅拷贝。
  • 我想我不明白您所说的“不看文档”是什么意思。如果你不看文档,也没有看到它被使用过(这会清楚它是一个函数还是方法),你首先怎么知道函数/方法的名称?
  • 创建字典的 shallow 副本是很常见的操作,dict 有一个专门的方法。对于列表,您可以使用标识切片 (lst[:])。
  • 查询是关于一般方法与函数,而不是关于深拷贝。

标签: python function methods


【解决方案1】:

问:为什么两者都有

还有更多给猫剥皮的方法:-)

太好了,我们至少有一个。 dict 也有它作为方法,可能是因为它方便 有它。

问:从性能角度来看,哪个更好用?

一般来说,如果你关心的话,你应该测量它(例如使用timeit)。不要期望有很大的差异。

问:如何快速判断某个任务是函数还是方法

... 不看文档? hsplit 是一个函数,而不是一个方法。

这真的很重要吗?随便挑几个,对你有好处。

无论如何,对于函数和方法的命名没有通用规则,这会对您有所帮助。

如果您需要了解更多关于 Python 中的变量、函数或方法的知识,请使用 help 学习

>>> help("a b".split)
Help on built-in function split:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.

>>> import string
>>> help(string.split)
Help on function split in module string:

split(s, sep=None, maxsplit=-1)
    split(s [,sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string s, using sep as the
    delimiter string.  If maxsplit is given, splits at no more than
    maxsplit places (resulting in at most maxsplit+1 words).  If sep
    is not specified or is None, any whitespace string is a separator.

    (split and splitfields are synonymous)

在 IPython 控制台中,此信息使用一个或两个问号表示:

>>> "a b".split?

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 2015-06-15
    • 2015-05-23
    • 2017-04-07
    • 2013-09-07
    • 2012-02-22
    • 2012-06-21
    • 2014-04-11
    相关资源
    最近更新 更多