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.
The boolean interpretation of zero is false. So your
if(v.vec[i]):
will be false ifv.vec[i]
is zero, and theif
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:(Also not sure why you're returning
"None"
instead ofNone
, but you can certainly adapt my example to do that if you want.)