python静态方法和类方法

静态方法是类和类的独立实例。它是在类范围中定义的方法。

它可以直接由类和实例被称为。

类方法和静态方法都要使用装饰器来定义,定义的基本格式是:

@staticmethod

def <function name>():

         #do something

类方法定义的基本格式是:

@ classmethod

def <function name>(cls):

         #do something

类方法与成员方法不同的是,它须要传入參数cls,cls代表类。

class Myclass():
	x='class';
	def __init__(self):
		self.x='instance';
	@ staticmethod
	def staticmd():
		print 'static method';
	@classmethod
	def classmd(cls):
		print cls.x;
		
	def inst(self):
		print self.x;

类的实例能够訪问静态方法。类方法,和成员方法

>>>test=Myclass()

>>>test.staticmd()

static method

>>>test.classmd()

class

>>>test.inst()

instance

类能够訪问静态方法和类方法,但不能訪问成员方法

>>>Myclass.staticmd()

static method

>>>Myclass.classmd()

class 

>>>Myclass.inst()

TypeError: unbound method inst() must be called with Myclass instance as first argument(got nothing instead)

静态方法能够被继承,以下的derived1类继承Myclass类,derived1类也有了静态方法。derived1的实例能够直接调用staticmd()方法

class derived1(Myclass):

         def__init__(self):

                   Myclass.__init__(self);

>>>d=derived1()

>>>d.staticmd()

static method

类方法也能够被继承,派生类的类的实例訪问类方法。将会自己主动调用派生类版本号的类方法,实现多态。

以下的derived2类继承自Myclass,derived2类能够调用类方法classmd(cls),此时cls指的是derived2.

class derived2(Myclass):

         x="derived2";

         def__init__(self):

                   Myclass.__init__(self);

>>>d2=derived2()

>>>d2.classmd()

derived2


版权声明:本文博主原创文章。博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/gcczhongduan/p/4815425.html