A better solution than passing to None - in this particular case, and not in general - is to consider the arr parameter for __init__ as an enumerated set of elements for initializing FruitContainer, and not for the array used for internal storage:
class FruitContainer: def __init__(self, arr=()): self.array = list(arr) ...
This will allow you to pass in other enumerated types to initialize your container that more advanced Python users are expected to expect:
myFruit = ('apple', 'pear') # Pass a tuple myFruitContainer = FruitContainer(myFruit) myOtherFruit = file('fruitFile', 'r') # Pass a file myOtherFruitContainer = FruitContainer(myOtherFruit)
It will also defuse another possible alias error:
myFruit = ['apple', 'pear'] myFruitContainer1 = FruitContainer(myFruit) myFruitContainer2 = FruitContainer(myFruit) myFruitContainer1.addTo('banana') 'banana' in str(myFruitContainer2)
With all the other implementations on this page, this will return True, because you accidentally overlaid the internal storage of your containers.
Note: This approach is not always the correct answer: "if not," then it is better in other cases. Just ask yourself: am I passing a set of objects or a mutable container? If the class / function with which I pass my objects modifies the store I gave it would be (a) unexpected or (b) desirable? In this case, I would say that it is (a); thus, calling a list (...) is the best solution. If (b), "if not None" would be the right approach.
Alice purcell
source share