我在下面創建了一些面向對象的Python代碼,其中創建了一個用戶實例(稱爲Ben)。這些函數正常工作,但我發現,當最後一行改爲ben.check_money = 100時,不會引發錯誤。我知道這是不正確的語法。添加正確的函數調用回然而,拋出上市的錯誤:TypeError: 'int' object is not callable
奇怪的Python OOP函數調用錯誤
原始代碼:
class User:
def __init__(self):
self.money = 200
self.score = 0
print('Created ')
def increase_money(self, amount):
self.money += amount
def decrease_money(self, amount):
self.money -= amount
def check_money(self):
print(self.money)
ben = User()
ben.check_money() # No error is thrown here
修改代碼1;
class User:
def __init__(self):
self.money = 200
self.score = 0
print('Created ')
def increase_money(self, amount):
self.money += amount
def decrease_money(self, amount):
self.money -= amount
def check_money(self):
print(self.money)
**ben = User()
ben.check_money = 100 # No error thrown here
ben.check_money() # Error is thrown here**
修改代碼2;
class User:
def __init__(self):
self.money = 200
self.score = 0
print('Created ')
def increase_money(self, amount):
self.money += amount
def decrease_money(self, amount):
self.money -= amount
def check_money(self):
print(self.money)
**ben = User()
ben.check_money = 100 # No error thrown here
ben.check_money # No Error is thrown here**
我的問題是;爲什麼錯誤只發生在某些情況下,取決於你以前如何調用它?人們會認爲它應該爲修改代碼1和修改代碼2輸出錯誤。