方法一:使用__call__
eg:
import os
class Command:
class _StaticCommand:
def __call__(self,command): os.system(command)
run = _StaticCommand()
if __name__ == ´__main__´:
Command.run("dir /w") #windows
Command.run("ls -l") #unix linux
实现原理:定义一个内部类(_StaticCommand),外层类(Command)有一个类属性run指向_StaticCommand的实例,关键在于定义
_StaticCommand的特殊方法__call__,这个方法当_StaticCommand的实例使用()时刻回调,(比如:_StaticCommand()()),
就好像实例是一个方法一样
方法二:使用python2.2以后提供的staticmethod类
import os
class Command:
def run(command):
os.system(command)
run = staticmethod(run) #staticmethod接受构造参数函数引用,此时run成为staticmethod类实例
if __name__ == ´__main__´:
Command.run("dir /w") #windows
Command.run("ls -l") #unix linux
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10294527/viewspace-122462/ ,如需转载,请注明出处,否则将追究法律责任。