0

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
  • 1
    get() is a dictionary method that will return None if the key (and associated value) are not present in the dictionary, otherwise it returns the value. None is used a little like NULL is in C/C++. Commented May 2, 2013 at 2:20
  • 1
    Not only are there no arrays in Python, you don't have a constructor in your code either. You do create an empty dict though. Commented May 2, 2013 at 2:22
  • You should also note that comments in python begin with #... /* */ is a syntax error in python Commented May 2, 2013 at 3:58

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

excellent answer.this is exactly the way I wanted it. :)Thank you very much.
1

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

1

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.

Comments

Your Answer

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.