Python中有函数,还是一切都是方法?

TIM*_*MEX 8 python oop methods function

或者一切都是方法吗?

因为一切都是一个对象,一个

def whatever:
Run Code Online (Sandbox Code Playgroud)

只是file.py的一种方法,对吗?

Dav*_*ebb 31

Python有功能.因为一切都是对象,所以函数也是对象.

所以,使用你的例子:

>>> def whatever():
...     pass
...
>>> whatever
<function whatever at 0x00AF5F30>
Run Code Online (Sandbox Code Playgroud)

当我们使用时,def我们创建了一个函数对象.例如,我们可以查看对象的属性:

>>> whatever.func_name
'whatever'
Run Code Online (Sandbox Code Playgroud)

在回答你的问题- whatever()不是一个方法file.py.最好将它视为绑定到whatever全局命名空间中的名称的函数对象file.py.

>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__d
oc__': None, 'whatever': <function whatever at 0x00AF5EB0>}
Run Code Online (Sandbox Code Playgroud)

或者以另一种方式看待它,没有什么能阻止我们将名称whatever完全绑定到另一个对象:

>>> whatever
<function whatever at 0x00AF5F30>
>>> whatever = "string"
>>> whatever
'string'
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以创建函数对象.例如,lambdas:

>>> somelambda = lambda x: x * 2
>>> somelambda
<function <lambda> at 0x00AF5F30>
Run Code Online (Sandbox Code Playgroud)

方法就像是作为函数的对象的属性.使它成为方法的方法是将方法绑定到对象.这会导致对象作为我们通常调用的第一个参数传递给函数self.

让我们SomeClass用方法somemethod和实例定义一个类someobject:

>>> class SomeClass:
...     def somemethod(one="Not Passed", two="Not passed"):
...         print "one = %s\ntwo = %s" % (one,two)
...
>>> someobject = SomeClass()
Run Code Online (Sandbox Code Playgroud)

让我们看一下somemethod属性:

>>> SomeClass.somemethod
<unbound method SomeClass.somemethod>
>>> someobject.somemethod
<bound method SomeClass.somemethod of <__main__.SomeClass instance at 0x00AFE030
Run Code Online (Sandbox Code Playgroud)

我们可以看到它是对象的绑定方法和类上的未绑定方法.所以现在让我们调用方法,看看会发生什么:

>>> someobject.somemethod("Hello world")
one = <__main__.SomeClass instance at 0x00AFE030>
two = Hello world
Run Code Online (Sandbox Code Playgroud)

因为它是一个绑定方法,所接收的第一个参数somemethod是对象,第二个参数是方法调用中的第一个参数.我们在类上调用方法:

>>> SomeClass.somemethod("Hello world")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method somemethod() must be called with SomeClass instance as first argument (got str instance instead)
Run Code Online (Sandbox Code Playgroud)

Python抱怨因为我们试图调用该方法而不给它一个适当类型的对象.所以我们可以通过"手动"传递对象来解决这个问题:

>>> SomeClass.somemethod(someobject,"Hello world")
one = <__main__.SomeClass instance at 0x00AFE030>
two = Hello world
Run Code Online (Sandbox Code Playgroud)

当您想要从超类调用特定方法时,可以使用此类型的方法调用 - 在类上调用方法.

(可以使用一个函数并将其绑定到类以使其成为一种方法,但这不是您通常需要做的事情.)