DeepNet
DeepNet

Reputation: 161

Python class instantiation with constraint

Say I would like to create a python class called Vector (this is only a toy example). I would write the following:

class Vector:
    def __init__(self, dimension, coordinates):
        self.dimension = dimension
        self.coordinates = coordinates

vec = Vector(3, [10, 20, 30])

Now say I write vec = Vector(3,[10, 20, 30, 40]), what I would like is an error of the form "invalid vector dimension".

In other words, first parameter should be equal to the length of the second parameter.

I realize it does not make a lot of sense here but again, it is just a toy example.

Upvotes: 2

Views: 58

Answers (1)

Tugay
Tugay

Reputation: 2214

you can try this:

class Vector:
    def __init__(self, dimension, coordinates):
        if len(coordinates) != dimension: raise ValueError("Coordinates doesn't match dimension")
        self.dimension = dimension
        self.coordinates = coordinates

In case you don't look at comments, @JeffUK noted:

Doing this as a one-liner has the benefit of showing the check in the traceback

Upvotes: 1

Related Questions