What is a 'NoneType' object?

2020-01-27 00:13发布

I'm getting this error when I run my python script:

TypeError: cannot concatenate 'str' and 'NoneType' objects

I'm pretty sure the 'str' means string, but I dont know what a 'NoneType' object is. My script craps out on the second line, I know the first one works because the commands from that line are in my asa as I would expect. At first I thought it may be because I'm using variables and user input inside send_command.

Everything in 'CAPS' are variables, everything in 'lower case' is input from 'parser.add_option' options.

I'm using pexpect, and optparse

send_command(child, SNMPGROUPCMD + group + V3PRIVCMD)
send_command(child, SNMPSRVUSRCMD + snmpuser + group + V3AUTHCMD + snmphmac + snmpauth + PRIVCMD + snmpencrypt + snmppriv)

9条回答
Root(大扎)
2楼-- · 2020-01-27 00:48

NoneType is simply the type of the None singleton:

>>> type(None)
<type 'NoneType'>

From the latter link above:

None

The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError.

In your case, it looks like one of the items you are trying to concatenate is None, hence your error.

查看更多
\"骚年 ilove
3楼-- · 2020-01-27 01:02

In the error message, instead of telling you that you can't concatenate two objects by showing their values (a string and None in this example), the Python interpreter tells you this by showing the types of the objects that you tried to concatenate. The type of every string is str while the type of the single None instance is called NoneType.

You normally do not need to concern yourself with NoneType, but in this example it is necessary to know that type(None) == NoneType.

查看更多
Summer. ? 凉城
4楼-- · 2020-01-27 01:03

A nonetype is the type of a None.

See the docs here: https://docs.python.org/2/library/types.html#types.NoneType

查看更多
Luminary・发光体
5楼-- · 2020-01-27 01:06

For the sake of defensive programming, objects should be checked against nullity before using.

if obj is None:

or

if obj is not None:
查看更多
该账号已被封号
6楼-- · 2020-01-27 01:07

One of the variables has not been given any value, thus it is a NoneType. You'll have to look into why this is, it's probably a simple logic error on your part.

查看更多
劫难
7楼-- · 2020-01-27 01:11

Your error's occurring due to something like this:
>>> None + "hello world"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>>>

Python's None object is roughly equivalent to null, nil, etc. in other languages.

查看更多
登录 后发表回答