DEV Community

codemee
codemee

Posted on • Updated on

犯了一個 Python 低級錯誤

剛剛寫了一個類似這樣的類別:

class PWM():
    def __init__(self, freq):
        self.freq = freq
    def freq(self, freq):
        self.freq = freq
Enter fullscreen mode Exit fullscreen mode

然後測試一下就炸掉了:

>>> a = PWM(20)
>>> a.freq("hello")
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
TypeError: 'int' object is not callable
Enter fullscreen mode Exit fullscreen mode

原來是物件的方法和物件的屬性同名, 所以在建立物件時, self.freq 已經在 init 中被設定為整數了, 等到執行 a.freq() 的時候, Python 發現這個 freq 是 int 物件, 並不能被叫用, 所以通知我 int 物件是不可叫用的喔!!

Top comments (0)