Python function uses multiple defaults or no defaults at all

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?

+4
source share
3 answers

The size and direction of the sound are like a tuple for me:

 class myVector(): def __init__(self, sd=(UNINITIALIZED, UNINITIALIZED)): try: self.size, self.direction = sd except (ValueError, TypeError) as e: raise ValueError('two values of size and direction must be specified') 

It is then called with a tuple of both size and direction if default values ​​are not needed.

If you do not want to change the semantics to require passing a tuple, the alternative, if you do not use other arguments, is to change sd to *args and do the same, which seems to me less explicit and means that you cannot use additional arguments for anything else.

+3
source

You can also define a class as follows:

 class myVector(): def __init__(self,*direction_and_size): if not len(direction_and_size): direction_and_size = [UNINITIALIZED, UNINITIALIZED] assert len(direction_and_size) == 2, "Please provide both parameters" self.direction, self.size = direction_and_size >>> v = myVector() >>> v = myVector(4,2) >>> v = myVector(4) AssertionError: Please provide both parameters 
+1
source

Something like that?

 class myVector(): def __init__(self, direction = -1, size = -1): if (-1 in (direction, size)): self.size, self.direction = (-1, -1) #do your own fault/error handling here #this just makes the example easier else: self.size = size, self.direction = direction c1 = myVector(1, 1) c2 = myVector(1) c3 = myVector() print(c1.direction, c2.direction, c3.direction) 

Outputs:
1 -1 -1

+1
source

Source: https://habr.com/ru/post/1492888/


All Articles