0

I define a class as below:

import numpy as np

class Vector:
    def __init__(self, v):
        self.v = v

I can create an instance of the class by doing the following:

p1 = np.array([0.0, 0.0, 0.0])

v1 = Vector(p1)
v2 = Vector(3)

My intention is that Vector always contains a vector in the 3D space. But, what is the proper way in python to make sure Vector will always be a 3-component vector?

2
  • 1
    You check it on __init__ and raise a ValueError if you received a bad value. Commented Jan 11, 2018 at 8:04
  • @KlausD. Thanks. If you have time, and feel like it, please post a short answer. Commented Jan 11, 2018 at 8:08

2 Answers 2

1

You can do this in two ways, which can be used simultaneously. First, at runtime:

class Vector:
    def __init__(self, v):
        if not isinstance(v, np.ndarray) or v.shape != (3,):
            raise ValueError("vector must be 3-dimensional array")
        self.v = v

Checking types like this is pretty much a standard convention in python. However, with Python 3.5+ the typing module was added, which allows for so called "type hints", which can get statically analyzed by your IDE or linter:

class Vector:
    def __init__(self, v: np.ndarray[float, shape=(3,)]):
        self.v = v

However, type hinting is not yet fully implemented for numpy (the above syntax is preliminary), see this tracking issue on GitHub.

Sign up to request clarification or add additional context in comments.

Comments

0

Not sure if this is the best way to do it, but for sure is one way. You can check with the following code:

import numpy as np
class Vector:
    def __init__(self, v):
        if isinstance(v, np.ndarray)  and v.size == 3:
            self.v = v
        else:
            raise ValueError('param is not an Array in the 3D space')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.