python的method_Python里method和function的区别

首先来看他们的定义,

函数function —— A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body.

方法method —— A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self).

首先,从概念上去分。函数可以看成一个数学上的概念,比如说完成加减乘除的函数。它其实有一个内在的约束:就是如果参数相同,对一个函数的每次调用返回的结果应该始终一样。

而方法是要和对象联系起来的。而且它有一个银行的参数:就是它所作用的对象。而这些更多地是在面向对象的语境里来说。

而从Python的定义来看,它将method作为function的一种特例来处理了。但当你在文档里看到instance method object和function object的说法时,你应该了解他们的差异。

>>> class MyClass:

i = 12345

def f(self):

return "hello world"

>>> x = MyClass()

>>> x.f.__class__

>>> MyClass.f.__class__

从上面的例子可以看出,一个是method object,一个是function object。

此外,Python里面还有staticmethod和classmethod的概念,他们和普通的method又有些区别。

->classmethod将类作为第一个隐含的参数

->而staticmethod没有任何隐含的参数,有点类似于Java里的static

>>> class MyClass:

i = 12345

@staticmethod

def f(self):

return "hello world"

def add(x, y):

return x+y

@classmethod

def foo(cls):

print(cls)

>>> MyClass.f.__class__

>>> MyClass.add.__class__

>>> MyClass.foo.__class__

>>> x = MyClass()

>>> x.f.__class__

>>> x.add.__class__

>>> x.foo.__class__

>>> x.foo()

当然,在很多语言里,这两者的区别没那么明显。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值