所以我有一個通用模塊,它包含我正在使用的數據和數據類型的處理函數。我希望能夠包括它像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