2016-07-06 76 views
0

我正在使用導入的RPi.GPIO函數庫來控制帶有Raspberry Pi的兩個直流電機的功率。其代碼如下:構造函數參數聲明一個類的實例時出錯

import RPi.GPIO as GPIO 

class Motor: 

    def _init_(self, MotorPin): 
     self.MotorControlPin = MotorPin 
     GPIO.setmode(GPIO.BOARD) 
     GPIO.setup(self.MotorControlPin, GPIO.OUT) 
     self.PWM = GPIO.PWM(self.MotorControlPin, 100) 
    def SetPower(self, Power): 
     self.PWM.start(Power) 

當我嘗試創建類的實例,RightMotor = Motor(12)的Python返回錯誤Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> RightMotor = Motor(12) TypeError: this constructor takes no arguments

蟒蛇IDLE似乎認爲_init_(self, Motor)函數不帶任何參數。我是否錯誤地使用了該功能?如果不是,問題是什麼?

回答

1

Python中的構造函數方法的名稱是__init__,開頭兩個下劃線,最後兩個下劃線。您的代碼定義_init_而不是Python,它只是另一種常規方法,不涉及對象構造。

+0

如果我曾見過一個粗心大意的錯誤!謝謝您的幫助! – Mension1234

相關問題