I define a class representing a vector:
''' An entity with size and direction ''' UNINITIALIZED = -1 class myVector(): def __init__(self,direction = UNINITIALIZED,size = UNINITIALIZED): self.direction = direction self.size = size
To use the class, I present two scenarios: either I know the vector clockwork during initialization, and then initiate it with these values:
v = myVector(4,2)
Or I donβt know about it, and then Iβm happy that it will get the default values.
However, when implementing the above implementation, the third scenario is implemented - the initiation of a vector using only the first argument:
v = myVector(4)
In this case, only the second parameter (size) is assigned the default value, and the resulting object does not make sense.
As I see it, the desired behavior in this case either uses both parameters or not. One way to implement this is to make an exception, if that is the case.
def __init__(self,direction = UNINITIALIZED,size = UNINITIALIZED): if (direction != UNINITIALIZED) and (size == UNINITIALIZED): raise Exception('Use both parameters or none') self.direction = direction self.size = size
Do you think this pythonic will be elegant?
source share