Python instance and class namespaces

371 views Asked by At

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.

2

There are 2 answers

0
BrenBarn On BEST ANSWER

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.)

0
Maurice Meyer On

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 !')