-1
我有問題,做一些驗證和改變了get()
方法的返回:類型錯誤對功能的方法/類屬性
class Foo(object):
def __init__(self, turnNum=1):
self._turnNum = turnNum
def set_turnNum(self, turnNum):
self._turnNum = turnNum
def get_turnNum(self):
return self._turnNum
但我發現了錯誤,每次我試圖像時間:
num = Foo()
num.set_turnNum(13)
if num.get_turnNum % 2 == 0:
print('Not works after all...')
...
我得到這個錯誤信息:
TypeError: unsupported operand type(s) for %: 'method' and 'int'
如果我嘗試CONV ERT到int
:
num = Foo()
num.set_turnNum(13)
if int(num.get_turnNum) % 2 == 0:
print('Not works after all...')
...
然後我得到這個其他錯誤消息:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'method'
可以看出,我與受保護的屬性嘗試。但是,爲了DIY,我也嘗試了公共和私人屬性。不幸的是,在Pytohn 3.5.2和3.6.1中,我得到了相同的結果。
什麼是在Python中這樣做的正確方法?
它不是一個屬性,它是一個方法:'get_turnNum()'。您可能想查看['@ property'](https://docs.python.org/3/library/functions.html#property)裝飾器。 –