003_python内置的@staticmethod详解

时间:2023-03-09 19:26:30
003_python内置的@staticmethod详解

python中的staticmethod 主要是方便将外部函数集成到类体中,美化代码结构,重点在不需要类实例化的情况下调用方法(类似java的静态方法)

如果你去掉staticmethod,在方法中加self也可以通过实例化访问方法也是可以集成代码

1)先看看不使用staticmethod的代码如何写的

#coding:utf-8
IND = 'ON'
def checkind():
return (IND == 'ON')
class Kls(object):
def __init__(self,data):
self.data = data
def do_reset(self):
if checkind():
print('Reset done for:', self.data)
def set_db(self):
if checkind():
self.db = 'New db connection'
print('DB connection made for:', self.data)
ik1 = Kls(12)
ik1.do_reset()
ik1.set_db()

输出=>

('Reset done for:', 12)
('DB connection made for:', 12)

2)再看看使用staticmethod的代码,用staticmethod包装的方法可以内部调用,也可以通过类访问或类实例化访问

#coding:utf-8
IND = 'ON' class Kls(object):
def __init__(self,data):
self.data = data
@staticmethod
def checkind():
return (IND == 'ON')
def do_reset(self):
if self.checkind():
print('Reset done for:', self.data)
def set_db(self):
if self.checkind():
self.db = 'New db connection'
print('DB connection made for:', self.data)
ik1 = Kls(12)
ik1.do_reset()
ik1.set_db() print(ik1.checkind())
print(Kls.checkind())

输出==>

('Reset done for:', 12)
('DB connection made for:', 12)
True
True