我在下面创建了一些面向对象的Python代码,其中创建了一个用户实例(称为Ben)。函数工作正常,但是,我发现当最后一行更改为本。检查你的钱=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都抛出一个错误。你知道吗
执行此操作时,
ben.check_money=100
将整数100
分配给本。检查你的钱属性。这个属性隐藏了这个方法本。检查你的钱(). 现在ben只有属性check_money
。因此,如果调用ben.check_money
,实际上是在调用属性,即int100
。ben.check_money()
正在调用该方法,但该方法现在被隐藏。你知道吗正确的方法可能是编写
setter()
方法:执行
ben.check_money = 100
时,用整数100
替换以前在ben
对象上调用的函数check_money
。将整数作为函数调用不起作用:将
ben.check_money()
设置为100后运行ben.check_money()
时也会出现类似的错误。你知道吗但是如果您只是访问
ben.check_money
,那么您并不是要求Python运行^{check_money
,只是将它返回给您,这样您就得到了整数值。你知道吗Python是一种动态语言,这意味着您可以在任何时候添加、删除或替换几乎任何对象中的任何内容,除非为此采取了措施
例如
在本例中,类
Fuu
只定义了1个属性/方法show
,但是您可以随时添加a
或fun
之类的附加属性/方法,或者替换show
之类的现有属性/方法,如示例所示。在您的代码中,您正在做的是将原来的check_money
方法替换为整数,而python什么也没说,因为它本质上允许这样做,不像更静态的lenguajes相关问题 更多 >
编程相关推荐