Home > Enterprise >  How to check parameter then define attribute python class
How to check parameter then define attribute python class

Time:12-04

I have a class Queue as below, In this class if I don't transmission capacity it will set isLimit and vice versa I don't know if there is a more efficient way

class Queue():
    def __init__(self, capacity=None):
        self._queue = list()
        if(capacity ==None):
            self.isLimit = False
        else:
            self.isLimit=True
            self.capacity = capacity

CodePudding user response:

Instead of use a variable isLimit, you can use only the variable capacity and verify if it's None or not:

class Queue():
    def __init__(self, capacity=None):
        self._queue = list()
        self._capacity = capacity
    
    def can_add_more(self):
        if self._capacity is None:  # Doesn't have a limit
            return True
        return len(self._queue) < self._capacity
  • Related