【发布时间】:2016-04-24 07:33:57
【问题描述】:
我在下面创建了一些面向对象的 Python 代码,其中创建了一个用户实例(称为 Ben)。这些功能正常工作但是,我发现当最后一行更改为 ben.check_money = 100 时,不会引发错误。我知道这不是正确的语法。但是,添加正确的函数调用会引发列出的错误:TypeError: 'int' object is not callable
原代码:
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 都抛出错误。
【问题讨论】:
标签: python oop object instance