所以我有一个通用模块,它包含我正在使用的数据和数据类型的处理函数。我希望能够包括它像from common import common
(或更好,但只是import common
)和使用功能,如common.howLongAgo(unixTimeStamp)
在Python中,如何在不传递实例的情况下使用类方法?
这是在我的公共模块需要什么? Common是一个由'common'类组成的模块。
模块foo.py
:
def module_method():
return "I am a module method"
class ModClass:
@staticmethod
def static_method():
# the static method gets passed nothing
return "I am a static method"
@classmethod
def class_method(cls):
# the class method gets passed the class (in this case ModCLass)
return "I am a class method"
def instance_method(self):
# An instance method gets passed the instance of ModClass
return "I am an instance method"
现在,进口:如果你想使类方法更加有用
>>> import foo
>>> foo.module_method()
'I am a module method'
>>> foo.ModClass.static_method()
'I am a static method'
>>> foo.ModClass.class_method()
'I am a class method'
>>> instance = ModClass()
>>> instance.instance_method()
'I am an instance method'
,导入一个Python模块中暴露方法
为什么这些功能在一个类首先?如果他们不需要'self',为什么不把它们移动到模块范围? – 2012-03-29 21:56:23
为了让它们脱离我的主Python文件 – Supernovah 2012-03-29 21:56:53
为了达到这个目的,你不需要把它们放在一个类中。只需将它们移动到一个模块并将它们留在模块级别即可。 – 2012-03-29 22:00:08