2016-12-06 37 views
0

這是我創建的一個類,用於與名爲「Waveplate」的設備進行通信。 「Waveplate」類繼承了serial.Serial Baseclass的屬性和方法。但正如你所看到的,基類serial.Serial需要被初始化。我在下面做的工作,我的問題是,這是最優雅的方式嗎?在類'__init__方法中初始化基類

import time 
import serial 

class WavePlate(serial.Serial): 
""" This class returns an instance that contains the attributes and methods of a ``serial.Serial`` object.  
""" 
    def __init__(self, p, brate): 
     """Here's the constructor. """ 
     self.p = p 
     self.brate = brate 

     serial.Serial.__init__(self, port=self.p, baudrate=self.brate, parity=serial.PARITY_NONE, 
          stopbits=serial.STOPBITS_ONE) 
+2

[Python's'super()'認爲超級!](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/) – AChampion

+1

通常,您首先調用基類「__init__」 ,然後做任何留給孩子的課程。它令我懷疑你明確地設置了'self.p'和'self.brate',*然後*將相同的值傳遞給'Serial .__ init__'。 – chepner

+0

謝謝你們.. super()聽起來超級棒 – Ravi

回答

0

你應該使用super

在Python 3:

class WavePlate(serial.Serial): 
""" This class returns an instance that contains the attributes and methods of a ``serial.Serial`` object.  
""" 
    def __init__(self, p, brate): 
     """Here's the constructor. """ 
     self.p = p 
     self.brate = brate 

     super().__init__(port=self.p, baudrate=self.brate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE) 

在Python 2:

class WavePlate(serial.Serial): 
""" This class returns an instance that contains the attributes and methods of a ``serial.Serial`` object.  
""" 
    def __init__(self, p, brate): 
     """Here's the constructor. """ 
     self.p = p 
     self.brate = brate 

     super(WavePlate, self).__init__(port=self.p, baudrate=self.brate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE) 

注意:在大多數情況下,你要電話在你的任何聲明之前的超類構造函數子構造函數。

+0

非常感謝..我刪除了傳遞給baseclass初始化步驟的實例屬性 – Ravi