您的位置:首页 > 编程语言 > Python开发

python中的静态方法和类方法

2016-08-18 19:03 387 查看
静态方法实际上就是普通函数,定义形式是在def行前加修饰符@staticmethod,只是由于某种原因需要定义在类里面。静态方法的参数可以根据需要定义,不需要特殊的self参数。可以通过类名或者值为实例对象的变量,已属性引用的方式调用静态方法

类方法定义形式是在def行前加修饰符@classmethod,这种方法必须有一个表示其调用类的参数,一般用cls作为参数名,还可以有任意多个其他参数。类方法也是类对象的属性,可以以属性访问的形式调用。在类方法执行时,调用它的类将自动约束到方法的cls参数,可以通过这个参数访问该类的其他属性。通常用类方法实现与本类的所有对象有关的操作。

##coding:utf-8
class TestClassMethod(object):

METHOD = 'method hoho'

def __init__(self):
self.name = 'leon'

def test1(self):
print 'test1'
print self

@classmethod
def test2(cls):
print cls
print 'test2'
print TestClassMethod.METHOD
print '----------------'

@staticmethod
def test3():
print TestClassMethod.METHOD
print 'test3'

a = TestClassMethod()
a.test1()
a.test2()
a.test3()
TestClassMethod.test3()


test1
<__main__.TestClassMethod object at 0x0000000003DDA5F8>
<class '__main__.TestClassMethod'>
test2
method hoho
----------------
method hoho
test3
method hoho
test3


实例方法隐含的参数为类实例,而类方法隐含的参数为类本身。
静态方法无隐含参数,主要为了类实例也可以直接调用静态方法。
所以逻辑上类方法应当只被类调用,实例方法实例调用,静态方法两者都能调用。

在贴一例,供参考:

class TestClassMethod(object):

METHOD = 'method hoho'

def __init__(self):
self.name = 'leon'

def test1(self):
print 'test1'
print self

@classmethod
def test2(cls):
print cls
print 'test2'
print TestClassMethod.METHOD
print '----------------'

@staticmethod
def test3():
print TestClassMethod.METHOD
print 'test3'

a = TestClassMethod()
a.test1()
a.test2()
a.test3()
TestClassMethod.test3()


test1
<__main__.TestClassMethod object at 0x0000000003DDA5F8>
<class '__main__.TestClassMethod'>
test2
method hoho
----------------
method hoho
test3
method hoho
test3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: