python - 通过创建处理程序类来避免重复代码

标签 python class gpio

我是 Python 新手,并试图避免一遍又一遍地重复相同的代码。我目前正在使用一个 Raspberry Pi,它在几个不同的类中使用 GPIO,因此不用编写

servoPin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPin,GPIO.IN)

在几个不同的类中,我希望将所有 GPIO 事件捆绑在某种 PinHandler 中。

所以,我为我的处理程序类想到了类似的东西

import RPi.GPIO as GPIO
 class PinHandler:
  def __init__(self):
   self.servoPin = 17
   GPIO.setmode(GPIO.BCM)
   GPIO.setup(self.servoPin,GPIO.IN)
  def getPinStatus(self,pin):
   return GPIO.input(pin)
  def addEventListener(self,functionName)
   GPIO.add_event_callback(self.servopin, functionName)

然后在我的其他类(class)中我需要输入的是

from pinHandler.py import PinHandler
import time

pinHandler = PinHandler()

pinHandler.addEventListener(myAwesomeFunction)

def myAwesomeFunction:
 pass

然后,这会将回调添加到 myAwesomeFunction 中,该回调超出了 pinHandler 的范围。我走在正确的轨道上还是有更好的方法?

最佳答案

更完整的OOP设计:

import RPi.GPIO as GPIO

class PinHandler:
    """
    Base class, wrapts all GPIO tasks
    """
    def __init__(self, pin):
        self.pin = pin
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.pin,GPIO.IN)

    def getPinStatus(self,pin):
       return GPIO.input(pin)

    def add_event_callback(self, callback)
        GPIO.add_event_callback(self.pin, callback)
<小时/>
from pinHandler.py import PinHandler


class Servo(PinHandler):
    """
    Spezialized class, handle all `Servo` related
    """
    def __init__(self):
        super().__init__(17)
        self.add_event_callback(self.event_listener)

    def event_listener(self, event):
        # handle event
        pass

Usage:

servo = Servo()

关于python - 通过创建处理程序类来避免重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58016482/

相关文章:

python - 添加附加 numpy 数组

python - 单个类中的多个 __init__ 有什么作用?

java - 我似乎不太理解 super() 关键字及其用法

c - STM32F103 GPIO 端口

javascript - 函数虽然有值但返回未定义

c - STM32 HAL GPIO中断计数太多

python - BeautifulSoup - 从多个页面获取文本

python - "think python 3"书中day_num问题的解决方案

python - 从另一个 Pandas DataFrame 引用一行

C#从另一个文件访问父类方法