2012-03-29 63 views
4

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

+5

爲什麼這些功能在一個類首先?如果他們不需要'self',爲什麼不把它們移動到模塊範圍? – 2012-03-29 21:56:23

+1

爲了讓它們脫離我的主Python文件 – Supernovah 2012-03-29 21:56:53

+0

爲了達到這個目的,你不需要把它們放在一個類中。只需將它們移動到一個模塊並將它們留在模塊級別即可。 – 2012-03-29 22:00:08

回答

25

方式直接上課:

>>> from foo import ModClass 
>>> ModClass.class_method() 
'I am a class method' 

您也可以import ... as ...以使其更易於閱讀:

>>> from foo import ModClass as Foo 
>>> Foo.class_method() 
'I am a class method' 

哪一些你應該使用多少有些口味的問題。我個人的經驗法則是:

  • 簡單實用的功能通常作用於之類的東西收藏,或執行一些計算或獲取一些資源應該是模塊的方法
  • 相關的一類功能,但不需要任何一個類或一個實例應該是靜態方法
  • 與某個類相關的函數,需要該類進行比較,或者訪問類變量應該是類方法。
  • 將作用於實例的函數應該是實例方法。
+0

在這樣的模塊範圍內暴露方法是否是通用代碼實踐?無論如何 - 它的工作非常感謝。 – Supernovah 2012-03-29 22:02:40

+1

用'@ classmethod'裝飾你的班級方法是非常清潔的 – Daenyth 2012-03-29 22:06:01

+0

這很普遍。標準庫有幾個例子。 'os'模塊是一個。 – brice 2012-03-29 22:06:59

2

,如果您有模塊common.py和功能是在課堂上共同

class common(object): 
    def howLongAgo(self,timestamp): 
      some_code 

,那麼你應該改變你的方法是靜態的方法絲毫裝飾@staticmethod

class common(object): 
    @staticmethod 
    def howLongAgo(timestamp): # self goes out 
      some_code 

這樣你不需要改變整個班級,你仍然可以在課堂上使用self.howLongAgo

0
class Test(object): 
    @classmethod 
    def class_method(cls): 
     return "class method" 

test = Test() 
print test.class_method() 

[[email protected] scar]$ python ~/test.py 
class method 

以上是使用現代Python對象進行classmethods的標準方式,而不是舊式類。

或者,您也可能意味着一個靜態方法:

class Test(object): 
    @staticmethod 
    def static_method(): 
     return "static method" 

test = Test() 
print test.static_method() 
[[email protected] scar]$ python ~/test.py 
static method 

使用哪種更有意義,你的問題。靜態方法通常應該被分離成它們自己的獨立功能,在那裏使用類是多餘的。

參考 http://pyvideo.org/video/880/stop-writing-classes

+0

是的,但問題是,做'test = Test()'你正在創建一個實例。這是我想要避免的。 – Supernovah 2012-03-29 22:15:17

相關問題