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

Error:python

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

代碼以下code

  

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參數得問題blog

如今讓咱們簡單瞭解一下Python中self的基礎信息:it

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

 

因此有兩種解決方法class

方法一:只傳一個參數,若是你想傳兩個參數,那就看方法二基礎

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)
相關文章
相關標籤/搜索