0

I am new to Python and familiar with Java and C#, so the follow code could be totally un-pythonic. I'm trying to get an indexed value of an instance of my Class Vector, in which the list of integers it contains is named vec.

class Vector:
def __init__(self,*args,**kwargs):
 if(args and args.length()>=2):
 self.dimension=args[0]
 self.vec=args[1]
 elif(kwargs):
 if(kwargs.get('vec')):
 self.vec=kwargs.get('vec')
 self.dimension=len(self.vec)
 elif(kwargs.get('n')):
 self.dimension=kwargs.get('n')
 nulllist=[]
 for x in range(0,kwargs.get('n')):
 nulllist.append(0)
 self.vec=nulllist
def __getitem__(v,i):
 if(v.vec[i]):
 return v.vec[i]
 else:
 return "None"

When I try to get v0 = Vector(n=2) assert(v0[0] == 0)

I get an assertion Error, because v0[0] returns "None" If I print(v0[0]) the print output is "None"

What did I do wrong? Thanks a lot in advance.

asked Dec 16, 2016 at 19:15
1
  • if(v.vec[i]) - what do you think that does? Commented Dec 16, 2016 at 19:18

2 Answers 2

1

The boolean interpretation of zero is false. So your if(v.vec[i]): will be false if v.vec[i] is zero, and the if block will not be entered.

It's unclear what you're attempting to test with that if anyway. If you're trying to test whether the element exists, that won't do it. You might be better off doing something like:

try:
 return v.vec[i]
except IndexError:
 return None

(Also not sure why you're returning "None" instead of None, but you can certainly adapt my example to do that if you want.)

answered Dec 16, 2016 at 19:19
Sign up to request clarification or add additional context in comments.

Comments

0

You should initialize self.vec in the constructor (for the case if and elif are not called).

class Vector:
 def __init__(self,*args,**kwargs):
 self.vec = None
 ...
v0 = Vector(n=2)
if v0.vec is not None:
 print('Vector defined')
else:
 print('ERROR: No Vector !')
answered Dec 16, 2016 at 19:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.