How to prevent the instantiation of class in python based on parameters passed in?

Lets say I have a class Vector2D that take x and y components. Because I have no interest in vectors with both components equal to zero, I want to prevent the object with both parameters passed equal to zero from being created in the first place and return None instead.

Upvotes: 0

Views: 99

Answers (2)

Reblochon Masque
Reblochon Masque

Reputation: 36662

You can use a factory function to verify that your parameters are not zero, thn return an instance of Vector2D, or raise an Error:

As mentioned in the comments by @jasonsharper, returning None is not a good idea, better to return an explicit error.

class NullVectorError(ValueError):
    pass


def make_non_null_vector(x: float, y: float) -> vector2D:
    if x and y:
        return Vector2D(x, y)
    raise NullVectorError('the parameters x:{x}, and y:{y}, cannot be both equal to zero') 

Upvotes: 1

quamrana
quamrana

Reputation: 39354

You could rename your class to RealVector2D and replace it with a new function:

def Vector2D(x, y):
    if x == 0 and y == 0:
        return None
    return RealVector2D(x, y)

Upvotes: 1

Related Questions