Python3基础-staticmethod
1、python staticmethod 返回函数的静态方法。
该方法不强制要求传递参数,如下声明一个静态方法
class test: @staticmethod def f(): print('hahhh') test.f() # 静态方法无需实例化 t1 = test() t1.f() # 也可以实例化后调用
执行结果如下
hahhh
hahhh
2、自定制的staticmethod
class StaticMethody: def __init__(self,func): self.func = func # print('====',self.func) def __get__(self, instance, owner): val = self.func() return val class test: @StaticMethody #dec =StaticMethody(dec) def dec(): print('hahhh') test.dec t1 =test() t1.dec
3、自定制的staticmethod,带参数
class StaticMethody: def __init__(self,func): self.func = func # print('====',self.func) def __get__(self, instance, owner): def feedbcak(*args,**kargs): val = self.func(*args,**kargs) return val return feedbcak class test: @StaticMethody #dec =StaticMethody(dec) def dec(name,age): print('hahhh',name,age) test.dec('xiaosu',200) t1 =test() t1.dec('susu',10)
以上代码执行结果如下
hahhh xiaosu 200
hahhh susu 10
浙公网安备 33010602011771号