python中的staticmethod装饰器(decorator)主要是方便将外部函数集成到类体中, 美化代码结构, 重点在可以不需要类实例化的情况下调用方法
如果去掉staticmethod,在方法中加self也可以通过实例化访问方法也是可以集成代码
1. 不使用staticmethod的代码如何写的:
IND = 'ON'
def checkind():
return (IND== 'ON')
class Kls(object):
def __init__(self, data):
self.data = data
def de_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包装的方法可以内部调用, 也可以通过类访问或类实例化访问:
IND = 'ON'
class Kls(object):
def __init__(self, data):
self.data = data
@staticmethod #加了@staticmethod,把外部方法集成到类体
def checkind():
return (IND== 'ON')
def de_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()
print(ik1.checkind())
print(Kls.checkind())
结果: Reset done for: 12 DB connection made for: 12 True True
两个代码的区别后者是加了@staticmethod, 把方法checkind()放入类中,既有在类内调用,也可以在类外通过类来调用(不一定要实例化)
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。