-2

I have the following code


    def __init__(self, calltime, slot):
        self.calltime = calltime
        self.slot = slot
        self.delay = np.random.normal(loc=0, scale=2.5,size=None)
        self.arrivalTime = self.slot + dt.timedelta(minutes=self.delay)
        self.scanWaitingTime = self.arrivalTime - self.slot
        self.scanStartTime =
        self.scanEndTime =

And I would like to specify conditions for my scanStartTime and scanEndTime as follows:

self.scanStartTime = if self.arrivalTime > slot:
                        return arrivalTime
                     else:
                        return slot

I know that I can not code it this way. Does anyone have an idea how I can solve this?

starlife
  • 13
  • 2
  • 3
    `self.arrivalTime if self.arrivalTime > slot else slot`? Or maybe `max((self.arrivalTime, slot))`? – jonrsharpe May 21 '19 at 21:44
  • 1
    Possible duplicate of [Does Python have a ternary conditional operator?](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) – mkrieger1 May 21 '19 at 21:44
  • @jonrsharpe's answer works. Keep in mind, that this will not update as self.arrivalTime or/and self.slot change through the class instance's life time. – Perplexabot May 21 '19 at 21:48

2 Answers2

1

You can use a condition like this:

self.scanStartTime=self.arrivalTime
if self.arrivalTime<=slot:
    self.scanStartTime=slot

This works by automatically setting it to arrivalTime, then checking if arrivalTime<=slot (the opposite of >). If it is, then it sets scanStartTime to slot, else it does nothing.

nerdguy
  • 174
  • 1
  • 16
  • It is best practice to keep the constructor method as clean as possible. Better to create separate functions to perform any calculation. Having separate functions will also help you understand your code later on, when it gets more complicated to keep track of what you did. – SV125 May 21 '19 at 21:57
0

You can create a separate function and call it in the constructor (init) method:

def __init__(self, calltime, slot):
    self.calltime = calltime
    self.slot = slot
    self.delay = np.random.normal(loc=0, scale=2.5,size=None)
    self.arrivalTime = self.slot + dt.timedelta(minutes=self.delay)
    self.scanWaitingTime = self.arrivalTime - self.slot
    self.scanStartTime = self.get_scan_start_time()
    self.scanEndTime = ""

def get_scan_start_time(self):
    if self.arrivalTime > self.slot:
        return self.arrivalTime
    else:
        return self.slot

SV125
  • 273
  • 1
  • 3
  • 13