2015-05-25 57 views
-3

在執行這個我收到提示說:Python對象()不帶參數

D:\SARFARAZ\Python>Python assignment_01.py 
Traceback (most recent call last): 
    File "assignment_01.py", line 35, in <module> 
    BankAcc1 = BankAcc('Sarfaraz',12345,50000) 
TypeError: object() takes no parameters 

代碼:

#Assignment_01 : Class Creation 
class BankAcc(object): 
    int_rate = 0.7 
    balance = 0 

    #def **_init_**(self, name, number, balance): --> error was in this line, I've corrected it now as below 
    def __init__(self, name, number, balance): 
     self.name = name 
     self.number = number 
     self.balance = balance 

    def withdraw(self, amount): 
     self.balance -= amount 
     return self.balance 

    def deposit(self, amount): 
     self.balance += amount 
     return self.balance 

    def add_interest(self): 
     self.interest = int_rate * self.balance 
     self.balance += self.interest 
     return self.balance 

'''class MinimumBalanceAccount(BankAccount): 
    def __init__(self, min_bal): 
     BankAccount.__init__(self) 
     self.min_bal = 500 

    def withdraw(self, amount): 
     if self.balance - amount < self.min_bal: 
      print ("Sorry, minimum balance must be maintained.") 
     else: 
      BankAccount.withdraw(self, amount)''' 

BankAcc1 = BankAcc('Sarfaraz',12345,50000) 
BankAcc2 = BankAcc1.withdraw(1000) 
print (BankAcc2) 

我試圖創建一個對象,然後試圖調用退出()方法 和撤回一些金額後打印餘額。

回答

2

您的__init__方法名錯字:

def _init_(self, name, number, balance): 

您需要使用強調在開始和結束。

如果沒有有效命名的__init__方法,Python會回退到object.__init__,該參數不帶參數。

+0

我怎麼會這麼傻,錯過了.. !!!感謝@Martijn Pieters – sarfarazit08