2009年11月17日 星期二

python object and static method

這是一則早該紀錄的文章,只能說我太懶惰了-.-,一切都是從這裡開始的,有天心血來潮想來review一下design pattern,結果跑去看良葛格的文章simple factory ,可是問題跑出來了,他下面的python code我不能跑,會出現錯誤跑出

TypeError: unbound method getMessage() must be called with MessageFactory instance as first argument (got str instance instead)

因為MessageFactory.getMessage("caterpillar@openhome.cc", "Hi")這行程式碼的MessageFactory沒有初始化出來,這和我們預期要的結果不同,我們原本就是要用工廠來封裝製作物件的過程,所以我們並不需要將messageFactory 的 instance建立出來,後來找到了class method differences in python : bound, unbound , and static文章,原來只要將def getMessage(addr, msg):上面加上@staticmethod decorator就不會有錯誤了!

另外也讓我了解到python的物件特性
Class Test(Object):
  def method_one(self):
    print "Called method_one"

  def method_two():
    print "Called method_two"

a_test = Test()
a_test.method_one()
a_test.method_two()
一個bound function 會被翻譯成為

a_test.method_one()  --->  Test.method_one(a_test)

所以使用method_two就會寫少一個argument
>>> a_test = Test()
>>> a_test.method_two()
Traceback (most recent call last): 
  File " ", line 1, in 
TypeError: method_two() takes no arguments (1 given)
如果你要改變這種情形 可以用decorator
class Test(object):
    def method_one(self):
        print "Called method_one"

    @staticmethod
    def method_two():
        print "Called method two"

Related Posts:

  • Flask Note 1想要來寫個Flask筆記, 這個系列會把一些看到, 或是曾經使用過的技術給記錄下來 環境需求:python2.7以上, python套件pip & virtualenv安裝 0. 建立virtualenv環境, 使用virturlenv目的就是為了建立一個乾淨的開發環境, 可以去掌握你撰寫的python程式跟其他package的相依性, 利於你的程式部署到其他機器上 $ pip install virtualenv Requ… Read More
  • FreeBSD + Apache2 + Mod_wsgi + Django最近在搞django , 之前試過在lighttpd上面用fastcgi跑django,不過光安裝就讓我一個頭兩個大,這次在不考慮效能的情況下想試試看用apache2 + mod_wsgi + django的安裝模式, 看是否有比較快, 安裝過程參考http://www.indexofire.com/blog/?p=243 幾乎是一模一樣啦,不過最後的地方我有特別標示清楚 1. FreeBSD是7.2,先更新完ports 2. Ports安装… Read More
  • python UnicodeEncodeError最近在玩qPlurk遇到的一個問題 UnicodeEncodeError: 'ascii' codec can't encode characters in position 42-44: ordinal not in range(128) 好像是因為再拿html的時候出的問題 解決的辦法就是利用 import sys reload(sys) sys.setdefaultencoding("utf-8") reference: 從這個站看… Read More
  • python object and static method 這是一則早該紀錄的文章,只能說我太懶惰了-.-,一切都是從這裡開始的,有天心血來潮想來review一下design pattern,結果跑去看良葛格的文章simple factory ,可是問題跑出來了,他下面的python code我不能跑,會出現錯誤跑出 TypeError: unbound method getMessage() must be called with MessageFactory instance as f… Read More
  • pythonkakashi@kakashi-laptop:~$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. import this The Zen of Python, by Tim Peters Be… Read More

2 則留言:

  1. 在 Python 3 中,@staticmethod 是不需要的,我的程式都是在 Python 3 環境中執行的。。XD

    回覆刪除
  2. 感謝啦,我到現在都還沒跳到python3 QQ"

    回覆刪除