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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值