python中类方法与实例方法的区别-python中类方法、类实例方法、静态方法的使用与区别...

1、如果你需要用实例来调用你的方法,那么在定义方法的时候,一定要把第一个参数设置成为self;

?2、如果你需要使用静态方法,那么你需要在方法前面加上@staticmethod修饰符;

?3、如果要使用类方法,那么你需要在方法前面加上@classmethod修饰符,并且在方法中至少使用一个参数,第一个参数在方法

中的作用就是代表改类本身。

????

#coding=gbk?

class C(object):

@staticmethod

def f1(arg): #here

is a static method. it's not necessary

只一个参数

#to have a

arg.

print 'arg:', arg

@classmethod

def f2(cls, arg):

#here is a class method. you have to take

第一个参数为类

#at least one arg. you can

use another name

#to replace the 'cls', but I

recommend you

#to use cls -- for most

python programmer

#use it.

print 'class name:', cls.__name__

print 'arg:', arg

def f3(self, arg):

#here is a instance method. Use 'self' in 第一个参数代表实例变量

#python is

just as 'this' in C++ or java.

print 'arg:', arg

def f4(arg): #no

error at here, but when you want to call this

这是错误的定义,缺少self

#method,

there will be an error. see it later.

print 'error:', arg

def test(): #

这是函数,不是方法(方法存在于类里)

c = C()

c.f1('cf1')

#OK

C.f1('Cf1')

#OK

c.f2('cf2')

#OK

C.f2('Cf2')

#OK

c.f3('cf3-1')

#OK

C.f3(c, 'cf3-2')

#OK

c.f4('cf4')

#Error

C.f4('Cf4')

#Error

if __name__ == '__main__':

test()

说明:

1、self

指的是你定义的这个类被调用创建了一个实例时,self就是这个实例。也就是说,self就是要使用你这个函数的实例的名称,这个self在类中必须要加,当然名字不一定是self,self只是传统变量名一直被沿用了而已。

2、类中的实例方法定义第一个参数必须是self,而普通函数(不在类中)的定义没有self参数。

转自:http://cache.baiducontent.com/c?m=9d78d513d9810ae902b0c8690c66c0101d43f6612bd6a0020fd3843995735a315017e1ac50200443939b733d47e90b4beb832b6f675d7de28cc8ff49d9ba852858d97a6b6d57d51d47c41edb931d769d7ecb47b9f144b2a7b174c0e88982c25757c9580e7882f28f5a0217cb64f01530e2a5984f155e10a7&p=8763cb15d9c043aa18bcc7710f089f&newp=9333831a84d012a05abd9b7d0f13cd231610db2151d4d31f&user=baidu&fm=sc&query=python?е???&qid=ef3722a200081e82&p1=23

?

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值