I'm learning about Python and am going through the OO-stage where I'm building a set of logic-gate classes.

To make the logic more resilient, I only want the user to be able to enter a value of 0 or 1 for the pin value in my binary class. I've currently done this by implementing a try/except in the getPin function, but I noticed I wasn't able to add something like:

except(ValueError) or (pinVal != 0 and pinVal != 1)

In the same line (you can, but it ignores the logic after the "or"), so I broke out the numeric checks in the else statement afterward.

Is this the best way to do this? Or is there a way to merge these two together? The fact that I have the identical line:

pinVal = self.invalidPinInput(self.getPin, pin)

Gives me some pause.

Full class code is below:

class BinaryGate(LogicGate):

    def __init__(self,n):
      self.pinA = self.getPinA()
      self.pinB = self.getPinB()

    def invalidPinInput(self, method, pin):
      print("Invalid input, value must be set to 0 or 1. Please enter 0 or 1.")
      return method(pin)

    def getPin(self, pin):
        pinVal = int(input("Enter Pin " + pin + " input for gate "+ str(self.getLabel()) +"-->"))
        pinVal = self.invalidPinInput(self.getPin, pin)
        if(pinVal != 0 and pinVal != 1):
          pinVal = self.invalidPinInput(self.getPin, pin)     
      return pinVal

    def getPinA(self):
      return self.getPin("A")

    def getPinB(self):
      return self.getPin("B")
  • \$\begingroup\$ I also just realized I'm setting value in my get function which should be changed, but the question on having the retry all on the same line still stands. \$\endgroup\$ – mverkruyse May 25 '19 at 16:39
  • 3
    \$\begingroup\$ Yeah, getter methods should not be abused like that. It would be good to include more context, such as the parent class and the code that invokes this code, so that we can give you better advice. \$\endgroup\$ – 200_success May 25 '19 at 16:44
  • \$\begingroup\$ I would answer this question, but currently I think it's unanswerable because we don't know how the code is being used. \$\endgroup\$ – Peilonrayz Jun 14 '19 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.