簡體   English   中英

有人可以向我解釋為什么我得到這個錯誤'int' object is not callable in my class

[英]can someone explain to me why I get this error 'int' object is not callable in my class

所以這是我的代碼

class Account:

    def __init__(self,owner,balance):

        self.owner = owner

        self.balance = balance

    def __str__(self):

        return (f" Account Owner : {self.owner} \t\n Account balance : ${self.balance}")

    def deposit(self,deposit):

        self.deposit = deposit

        self.balance = self.balance+self.deposit

        print(f"Deposit Accepted : {self.deposit}")

acc1 = Account("John",6000)

問題是當我兩次調用存款方法時出現此錯誤 TypeError: 'int' object is not callable 第一次調用我沒有收到任何錯誤,但第二次我收到上一個錯誤

問題:在第一次調用deposit方法時,您正在創建一個與方法同名的實例變量self.deposit 下次調用deposit時,它實際上是在嘗試調用實例變量,因此int is not callable錯誤。

解決方案:您可以通過修改您的deposit方法來糾正錯誤,使其不會創建實例變量,因為它沒有在 function 的 scope 之外使用。

這是修改后的 function:

def deposit(self, deposit):
    self.balance = self.balance + deposit
    print(f"Deposit Accepted : {deposit}")

如果您確實需要創建一個實例變量來存儲存款,那么只需使用不同的(唯一)名稱。

您正在調用方法存款。 但這也是您傳入的變量的名稱。當您運行self.deposit = deposit時,您實際上是用 integer 替換了該方法。 解決方案是使用不同的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM