I see a piece of python code
/*Constructor*/
self.matrix={}
/*my funciton*/
if(self.matrix.get((packet.src,packet.dst))==None):
does a python array get initialized to None? What does none represent ? Is the above comparision correct?I am a newbie in python and trying to relate to C++ concepts
3 Answers 3
self.matrix isn't an array, it is a dict. This is comparable to a std::map in C++. From your usage, it is like a std::map<std::pair<srcType, dstType>, valueType>. (Note that dicts can hold variant types both in the key and the value -- I'm only assuming that it'll always use a tuple of 2 elements as the key.)
And no, self.matrix isn't initialized to None. dict.get() returns None if it can't find a match. As an alternative, [] throws a KeyError exception if it can't find a match.
1 Comment
matrix is a dictionary not a list. This is best explained by an example:
>>> dic = {}
>>> dic['a'] = 1
>>> dic['a']
1
>>> dic.get('a')
1
>>> dic.get('b') == None
True
>>> dic['b']
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
dic['b']
KeyError: 'b'
Comments
An empty list or dictionary in Python (Python programs don't generally use arrays, although there is a module for them) are "empty list object" and "empty dictionary object", respectively, not None. The get() function returns None as a way of saying "the dictionary doesn't contain a value for that key". None is a constant value that is not equal to any scalar value (like integers, strings, etc.) or any instance of any class. It's just what it says--this is not a thing. C/C++ has no such concept for scalar types like ints and floats, but a NULL pointer is guaranteed to be unequal to any valid pointer to an object.
In the OOP model, None is a subclass of every class, but Python doesn't really care that much since it's more loosely typed.
get()is a dictionary method that will returnNoneif the key (and associated value) are not present in the dictionary, otherwise it returns the value.Noneis used a little likeNULLis in C/C++.dictthough.#.../* */is a syntax error in python