2015/08/06

Python Property Setter Getter TypeError int

以前寫 Java 的時候,需要寫 getX() 以及 setX(),但最近在學習 Python 時才知道 pythonic 方式可以直接使用 property 就可以達到 getter 以及 setter 效果。

只是我使用 property 的 Setter 遇到了以下問題,就把整個過程記錄下來提供其他人做參考。
TypeError: 'int' object is not callable

但在 Python 內使用 property 時仍然要注意,在《Python 慣用語 - 14 用 property 取代 getters, setters》裏有提到:
要避免對吃資源的 method 使用 property ,因為存取 attribute 給人的感覺是很輕量的操作,這樣使用該物件的人就有可能忽視效能的問題。

自定 Setter Getter


以下的寫法是一般在 Java 內的寫法,需要特別指定 getX() 以及 setX()。

其實如果 Python 程式是要被其他程式呼叫時,我還是會使用這種方式,因為這種方式的優點是其他程式的使用習慣不需要特別改變,也很直覺,雖然這個也算是一種包袱啦。
#!/usr/bin/env python

class Example(object):
    def __init__(self, x=None):
        self._x = x

    def getX(self):
        return self._x
    
    def setX(self, value):
        self._x = value

e = Example(10)
print e.getX()
e.setX(30) #setter
print e.getX() #getter


JosedeMacBook-Pro:python sunjose$ python test.py
10
30


使用 Python Property 的 Setter Getter


如果只被 Python 使用,又不是吃資源的 method 時,我就會使用 property 的方法,但使用 Setter 時遇到了問題:
TypeError: 'int' object is not callable

在 Google 後我才發現原來是我使用 property 的 Setter 方法錯誤,我用e.x(30),但其實 Setter 直接用 = 即可。
#!/usr/bin/env python

class Example(object):
    def __init__(self, x=None):
        self._x = x

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

e = Example(10)
print e.x
e.x = 30 #setter
print e.x #getter


JosedeMacBook-Pro:python sunjose$ python test.py
10
30




沒有留言:

張貼留言