600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python中类方法与实例方法的区别-python中类方法 类实例方法 静态方法的使用与区别...

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

时间:2022-12-12 03:27:20

相关推荐

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参数。

转自:/c?m=9d78d513d9810ae902b0c8690c66c0101d43f6612bd6a0020fd3843995735a315017e1ac5043939b733d47e90b4beb832b6f675d7de28cc8ff49d9ba852858d97a6b6d57d51d47c41edb931d769d7ecb47b9f144b2a7b174c0e88982c25757c9580e7882f28f5a0217cb64f01530e2a5984f155e10a7&p=8763cb15d9c043aa18bcc7710f089f&newp=9333831a84d012a05abd9b7d0f13cd231610db2151d4d31f&user=baidu&fm=sc&query=python?е???&qid=ef3722a200081e82&p1=23

?

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。