Checking if an object is in a determined class python

Question:

I’m trying to create a class representing vectors (called Vector) and one representing matrices (called Matrix). The problem arised in defining the matrix-vector product: I don’t see errors in the actual implementation, but I tried to add a check before the code to raise an error if the second element wasn’t a Vector and it doesn’t work.

I tried using the isinstance() function to check if the vector i was interested in was actually a Vector, but it raises a name error.

I’m not able to find any advice about it and I’m certain that it’s because I didnt understand how the function works.

Here’s my code:

class Vector: #defined in the module Vector
 def __init__(self):
  pass

class Matrix:
 from Vector import Vector  #the module is called Vector as the class
 def __init__(self):
  pass
 def __mul__(self,other): #method called by self*other, if other is vector should perform matrix-vector multiplication
  if isinstance(other,Vector): 
   pass #I didn't write the actual content because the error arises on the condition
  pass


from Matrix import Matrix #the classes were defined in a different module
from Vector import Vector #the classes were defined in a different module

v=Vector()
A=Matrix()
A*v

The error message was:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "DesktoppythonMatrix.py", line 82, in __mul__
    if isinstance(other,Vector):
NameError: global name 'Vector' is not defined

I imported both the classes Vector and Matrix before using the method __mul__ and in the code for the class Matrix I imported the class Vector again so I could use the class Matrix separately.

The classes are defined in two different files saved in the same directory.

Any hint on how to fix the problem?

Asked By: Orazio Cherubini

||

Answers:

It looks like you’ve defined your two classes in separate modules. That’s OK (though not required in Python), but if you do that, you need to import one class in the other class’s module if you want them to be able to refer to each other by name. If they’re so highly coupled together that they’d both need to access the other, you should probably put them in the same module.

Answered By: Blckknght
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.