Python基礎-TypeError:takes 2 positional arguments but 3 were given


Error:

  今天寫一段簡單類定義python代碼所遇到報錯問題:TypeError: drive() takes 2 positional arguments but 3 were given

代碼如下

  

class Car:
    speed = 0
    def drive(self,distance):
        time = distance / self.speed
        print(time)

bike = Car()
bike.speed=60
bike.drive(60,80)

后經排查,才發現是類定義中 def drive(selef,distance) 方法中self參數得問題

現在讓我們簡單了解一下Python中self的基礎信息:

self,表示創建的類實例本身,方法內部,就可以把各種屬性綁定到self,因為self就指向創建的實例本身。在創建實例的時候,就不能傳入空的參數了,必須傳入與方法匹配的參數,但self不需要傳,Python解釋器會自己把實例變量傳進去。

 

所以有兩種解決方法

方法一:只傳一個參數,如果你想傳兩個參數,那就看方法二

class Car:
    speed = 0
    def drive(self,distance):
        time = distance / self.speed
        print(time)

bike = Car()
bike.speed=60
bike.drive(80)

 

方法二:

class Car:
    speed = 0
    def drive(self,distance,speed):
        time = distance / speed
        print(time)
bike = Car()
bike.drive(80,50)

 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM