简体   繁体   English

我收到一个类型错误。 我如何解决它?

[英]I'm getting a TypeError. How do I fix it?

I commonly get uncaught exceptions (errors) from my Python code that are described as TypeError s.我通常从我的 Python 代码中得到未捕获的异常(错误),这些代码被描述为TypeError After considerable experimentation and research, I was able to collect the following examples (and minor variations):经过大量的实验和研究,我能够收集到以下示例(以及细微的变化):

TypeError: func() takes 0 positional arguments but 1 was given
TypeError: func() takes from 1 to 2 positional arguments but 3 were given
TypeError: func() got an unexpected keyword argument 'arg'
TypeError: func() missing 1 required positional argument: 'arg'
TypeError: func() missing 1 required keyword-only argument: 'arg'
TypeError: func() got multiple values for argument 'arg'
TypeError: MyClass() takes no arguments
TypeError: unsupported operand type(s) for +: 'int' and 'str'
TypeError: can only concatenate str (not "int") to str
TypeError: '>' not supported between instances of 'int' and 'str'
TypeError: can't multiply sequence by non-int of type 'float'
TypeError: string indices must be integers
TypeError: %d format: a number is required, not str
TypeError: not all arguments converted during string formatting
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
TypeError: a bytes-like object is required, not 'str'
TypeError: bad operand type for abs(): 'str'
TypeError: descriptor 'to_bytes' for 'int' objects doesn't apply to a 'str' object
TypeError: 'int' object is not iterable
TypeError: cannot unpack non-iterable int object
TypeError: 'int' object is not callable
TypeError: 'int' object is not subscriptable

I have also seen custom messages when trying to use a function, method or class from a library.在尝试使用库中的 function、方法或 class 时,我还看到了自定义消息。

What is a TypeError ?什么是TypeError What do messages like this mean?像这样的消息是什么意思? How can I understand and fix the problem?我怎样才能理解和解决问题?


If your question was closed as a duplicate of this, please carefully read and follow the advice here, and try todebug the code and research any remaining problem before asking again.如果您的问题与此重复,请仔细阅读并遵循此处的建议,并在再次提问之前尝试调试代码并研究任何剩余的问题。 Stack Overflow is not a debugging service. Stack Overflow 不是调试服务。

A valid, non-duplicate question about a TypeError will ask why a specific, minimal, reproducible example causes a TypeError , and explain what you expected to happen instead and why.关于TypeError的有效、非重复问题将询问为什么特定的、最小的、可重现的示例会导致TypeError ,并解释您期望发生的情况以及原因。

What is a TypeError ?什么是TypeError

It means exactly what it sounds like: there is an Error that is caused by the Type of one or more of the values in the code.这意味着它听起来像:有一个Error是由代码中一个或多个值的Type引起的。 It's obvious what an error is, so let's explain the concept of "type" in more detail.很明显错误是什么,所以让我们更详细地解释“类型”的概念。

In a Python program, every object has a type .在 Python 程序中,每个 object 都有一个类型 By "object" (equivalently in Python, "value") we mean something that can be given a name in the source code. “对象”(相当于 Python 中的“值”)是指可以在源代码中命名的东西。 Most names are simple variables: if we write x = 1 , then 1 is an object, it has a name x , and its type is int - the type itself has a name.大多数名字都是简单的变量:如果我们写x = 1 ,那么1是一个 object,它有一个名字x ,它的类型是int - 类型本身有一个名字。

"Type" means more or less what it sounds like: it tells you what kind of thing something else is. “类型”或多或少意味着它听起来的样子:它告诉你其他东西是什么类型的东西 1 , 2 and 3 are all integers; 1 3 2 they have the same type, int .它们具有相同的类型int You can think of it as representing the concept of an integer.您可以将其视为代表 integer的概念

Not every type has a built-in name.并非每种类型都有内置名称。 For example, functions are objects (most other languages don't work this way,), and they have a type.例如,函数是对象(大多数其他语言不以这种方式工作),并且它们具有类型。 but we can't directly refer to that type by name in our code.但我们不能在代码中直接按名称引用该类型。

Every type does have a representation as an object, however, whether it's named or not.每种类型都有一个表示为object ,但是,无论它是否被命名。 You can use the built-in type to get such a "type object":您可以使用内置type来获取这样的“类型对象”:

>>> type(1) # the result from this...
<class 'int'>
>>> int # is the same:
<class 'int'>
>>> type(int) # We can look a bit deeper:
<class 'type'>
>>> def func():
...     pass
>>> type(func) # and get types that aren't named:
<class 'function'>
>>> type(type) # and there's this special case:
<class 'type'>

Notably, the type of type is type itself .值得注意的是,类型的typetype本身

You may notice that Python (3.x) displays these type objects with the word class .您可能会注意到 Python (3.x) 使用单词class显示这些类型对象。 This is a useful reminder: when you create a class , you are defining a new type of data .这是一个有用的提醒:当您创建class时,您正在定义一种新的数据类型 That is the purpose of classes.这就是上课的目的。

What do messages like this mean?像这样的消息是什么意思?

We can break the examples down into a few categories:我们可以将示例分为几类:

TypeError: func() takes 0 positional arguments but 1 was given
TypeError: func() takes from 1 to 2 positional arguments but 3 were given
TypeError: func() got an unexpected keyword argument 'arg'
TypeError: func() missing 1 required positional argument: 'arg'
TypeError: func() missing 1 required keyword-only argument: 'arg'
TypeError: func() got multiple values for argument 'arg'
TypeError: MyClass() takes no arguments

These exceptions are telling you that the arguments (the things you put between the () ) for calling func (or creating an instance of MyClass ) are wrong.这些异常告诉您调用func (或创建MyClass的实例)的 arguments (您放在()之间的东西)是错误的。 Either there are too many, not enough, or they are not properly labelled.要么太多,要么不够,要么没有正确标记。

TypeError: unsupported operand type(s) for +: 'int' and 'str'
TypeError: can only concatenate str (not "int") to str
TypeError: '>' not supported between instances of 'int' and 'str'
TypeError: can't multiply sequence by non-int of type 'float'

These exceptions are telling you that the left-hand side and right-hand side of an operator (a symbol like + or > or ^ , used to compute a result ) don't make sense .这些异常告诉您运算符的左侧和右侧(用于计算结果的+>^之类的符号)没有意义 For example, trying to divide or subtract strings, or repeat a string a non-integer number of times .例如,尝试对字符串进行除法或减法,或者将字符串重复非整数次 As a special case, you can use + between two strings (or lists, or tuples), but it doesn't "add" them in a mathematical sense.作为一种特殊情况,您可以在两个字符串(或列表或元组)之间使用+ ,但它不会在数学意义上“添加”它们。 If you try to use + between an integer and a string, the error message will be different depending on the order.如果您尝试在 integer 和字符串之间使用+ ,则错误消息将根据顺序而有所不同。

TypeError: %d format: a number is required, not str
TypeError: not all arguments converted during string formatting

These ones are a bit tricky.这些有点棘手。 The % operator is used to get the modulus (remainder when dividing numbers), but it can also be used to format strings by replacing some placeholders. %运算符用于获取模数(除数时的余数),但它也可用于通过替换一些占位符来格式化字符串。 (This is an outdated system that's hard to get right and has weird special cases ; in new code, please use f-strings or the .format method.) (这是一个过时的系统,很难改正并且有奇怪的特殊情况;在新代码中,请使用 f-strings 或.format方法。)

An error occurs because the placeholders in the string on the left-hand side don't match up with what's on the right-hand side.发生错误是因为左侧字符串中的占位符与右侧的内容不匹配。 In the second case, it's likely that you actually wanted to calculate a modulus, so the left-hand side should be a number (most likely an integer) instead.在第二种情况下,您可能实际上想要计算模数,因此左侧应该是一个数字(很可能是一个整数)。 It's debatable whether these should be ValueError s instead, since it could be that the contents of the string are wrong.这些是否应该改为ValueError是有争议的,因为字符串的内容可能是错误的。 However, Python cannot read your mind.但是,Python 无法读懂您的想法。

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
TypeError: bad operand type for abs(): 'str'

These mean that something wrong was passed to a built-in function (or another callable, such as a type).这意味着错误的东西被传递给了内置 function(或其他可调用对象,例如类型)。 Functions that you get from a library may raise their own TypeError s with custom messages.从库中获取的函数可能会使用自定义消息引发它们自己的TypeError The message should be pretty straightforward.信息应该非常简单。

TypeError: descriptor 'to_bytes' for 'int' objects doesn't apply to a 'str' object

This one is very unusual, and most people who ask this question would never run into it ( except maybe with the datetime standard library module ).这是一个非常不寻常的问题,大多数提出这个问题的人都不会遇到它(除了datetime标准库模块)。 It happens because of trying to use a method as if it were a function, but giving it the wrong type of thing for self : for example, int.to_bytes('1') .发生这种情况是因为尝试使用一种方法,就好像它是 function 一样,但是给它错误的self类型:例如int.to_bytes('1') The code is wrong because '1' is a string, and strings don't support .to_bytes .代码错误,因为'1'是一个字符串,而字符串不支持.to_bytes Python will not convert the string to integer; Python 不会将字符串转换为 integer; and it cannot give an AttributeError instead because to_bytes was looked up in the class , not on the string.并且它不能给出AttributeError而是因为to_bytes在 class中查找的,而不是在字符串中。

TypeError: 'int' object is not iterable
TypeError: cannot unpack non-iterable int object
TypeError: 'int' object is not callable
TypeError: 'int' object is not subscriptable

These mean exactly what they sound like.这些正是它们听起来的意思。 "iterable" means "able to be iterated" ; “iterable”的意思是“能够被迭代” ie, checked repeatedly to get separate values.即,反复检查以获得单独的值。 This happens in for loops, comprehensions and when trying to convert to list etc. The "unpack" variation of the message results from trying to use unpacking syntax on the non-iterable.这发生在for循环、理解以及尝试转换为列表等时。消息的“解包”变体是由于尝试在不可迭代对象上使用解包语法造成的。

"callable" means "able to be called" ; “callable”的意思是“能够被调用” to "call" something is to write () after it (possibly with arguments between the () ). “调用”某事是在它之后写() (可能与()之间的 arguments )。 Code like 1('test') doesn't make sense because 1 isn't a function (or a type).1('test')这样的代码没有意义,因为1不是 function (或类型)。

"subscriptable" means "able to be subscripted" ; “可下标”的意思是“可以下标” here, "subscripting" means either using slice syntax ( x[1:2:3] ), or indexing or looking for a key ( x['test'] ).在这里,“下标”意味着要么使用切片语法( x[1:2:3] ),要么索引或查找键( x['test'] )。 We can only do this with sequences (like list s or str ings) and mappings (like dict s).我们只能使用序列(如liststr )和映射(如dict )来做到这一点。

How can I understand what went wrong, and fix the code?我怎样才能理解出了什么问题,并修复代码?

First, look at the traceback to see where in the code the error occurs.首先,查看回溯以查看错误发生在代码中的哪个位置。 If it's in a library, work backwards to the point where your code uses the library.如果它在库中,请向后工作到您的代码使用该库的位置。 Then read the error message carefully, and compare it to the code, to figure out what causes the complaint.然后仔细阅读错误信息,并将其与代码进行比较,找出导致投诉的原因。 Finally, think carefully: is the operation wrong, or the values ?最后,仔细想想:是操作错了,还是价值观错了?

Some more specific advice for things that might not be obvious:对于可能不明显的事情的一些更具体的建议:

In general一般来说

Did you perhaps reassign the name of a built-in callable , such as str or input or list ?您是否可能重新分配了内置 callable 的名称,例如strinputlist Did you try to reuse a name for two different things (for example, a function and some global data that it uses)?您是否尝试为两个不同的事物重用名称(例如,function 和它使用的一些全局数据)? Names in Python can only refer to one thing at a time. Python 中的名称一次只能指一件事。 If you use, say, list as a variable name, then it isn't also the name of "the abstract concept of a list" any more, so you can't use it to create more lists (which includes converting other things to lists).例如,如果您使用list作为变量名,那么它不再是“列表的抽象概念”的名称,因此您不能使用它来创建更多列表(包括将其他内容转换为列表)。 If you create a global variable months with a list of strings, and then write a function months , the function replaces the list, and the function's code can't look up the list.如果用字符串列表创建一个全局变量months ,然后写一个function months ,function替换列表,函数的代码无法查找列表。

Similarly, if you try to make a class that uses the same name for an method as for a data attribute of the instances , that will cause the same problem.类似地,如果您尝试创建一个 class ,该方法使用与实例的数据属性相同的名称,这将导致相同的问题。 (There's also a tricky special case with @staticmethod ). @staticmethod还有一个棘手的特殊情况)。

Sometimes people expect to be able to use a list like a Numpy array, and "broadcast" an operation or a function call to each element of the list.有时人们希望能够使用像 Numpy 数组这样的列表,并对列表的每个元素“广播”一个操作function 调用 That doesn't work.那是行不通的。 Use a list comprehension instead .请改用列表推导

Consider whether you need to handle None as a special case .考虑是否需要将None作为特殊情况处理 But try to avoid getting into that situation in the first place;但首先要尽量避免陷入这种情况; "special cases aren't special enough to break the rules", as they say.正如他们所说,“特殊情况不足以打破规则”。

If the error mentions a 'str' type and you thought it should be a number如果错误提到“str”类型并且您认为它应该是一个数字

Did you get it from the input function?你是从input function 得到的吗? That gives you a str , even if it looks like a number.这给了你一个str ,即使它看起来像一个数字。 Please see How can I read inputs as numbers?请参阅如何将输入读取为数字? . .

If the error mentions a 'function' type or 'type' type如果错误提到“函数”类型或“类型”类型

Did you forget to call the function, or create an instance of a class?您是否忘记调用 function 或创建 class 的实例?

If the error is from function arguments如果错误来自 function arguments

The error message will tell you the name of the function;错误信息会告诉你function的名称; so look at the part of the line that calls that function, and check the arguments.因此,请查看调用 function 的行的部分,并检查 arguments。 Is there a correct number of positional arguments?位置 arguments 的数量是否正确? Is there a keyword argument that must be provided, and is missing?是否有必须提供的关键字参数,但缺少? Is there a keyword argument that shouldn't be provided?是否存在不应提供的关键字参数? Is there a positional argument that is also provided by keyword?关键字是否也提供了位置参数?

If you are writing a method for a class, remember to allow for self .如果您正在为 class 编写方法,请记住允许self It is necessary for instance methods.实例方法是必需的。 If you are calling a method, keep in mind that self will be counted as an argument (both for the amount "required" and the amount "given").如果您正在调用一个方法,请记住self将被视为一个参数(“需要”的数量和“给定”的数量)。

If you are using a callback that takes arguments from an indirect source, check the source .如果您使用从间接源获取 arguments 的回调,请检查源

If you are trying to create an instance of your own class, and get an TypeError from __init__ , make sure that you actually wrote an __init__ .如果您尝试创建自己的 class 的实例,并从__init__获取TypeError请确保您确实编写了__init__

If you don't know what the arguments should be, check the documentation .如果您不知道 arguments 应该是什么,请查看文档 If the arguments make sense, maybe the function is wrong - make sure you didn't confuse it for another one in the same library.如果 arguments 有意义,那么function可能是错误的 - 确保您没有将它与同一个库中的另一个混淆。

If the error is from operands of an operator如果错误来自运算符的操作数

Make sure the operator is correct for what you want the code to do (for example: ^ is not exponentiation; you want ** ), and then check the operand types.确保运算符对于您希望代码执行的操作是正确的(例如: ^不是求幂;您想要** ),然后检查操作数类型。 In most cases, it will be appropriate to convert the type - but think carefully.在大多数情况下,转换类型是合适的——但请仔细考虑。 Make sure the operation will make sense with the new types.确保操作对新类型有意义。 For example, if the code is l + 'second' , and l is a list that currently contains ['first'] , chances are good we don't want to concatenate strings, but instead create a modified list that also has 'second' as an element.例如,如果代码是l + 'second' ,并且l是一个当前包含['first']list ,那么我们很可能不想连接字符串,而是创建一个也有'second'的修改列表'second'作为一个元素。 So actually we wanted to "add" another list : l + ['second'] .所以实际上我们想“添加”另一个列表l + ['second']

If the error is from string formatting如果错误来自字符串格式

Seriously, did you intend to do string formatting?说真的,您是否打算进行字符串格式化? If you do want to format a string, consider using f-strings or the .format method - these are easier to debug, and have fewer special cases.如果您确实想格式化字符串,请考虑使用 f-strings 或.format方法- 这些更容易调试,并且特殊情况更少。 But more likely, the left-hand side is some string like '1' that should have been converted to int (or maybe float ) first.但更有可能的是,左侧是一些像'1'这样的字符串,应该首先转换为int (或者可能float )。

A bad operand type for a unary operator一元运算符的错误操作数类型

This can be caused by a stray comma .可能是由杂散逗号引起的 'a', + 'b' is not the same as 'a' + 'b' ; 'a', + 'b''a' + 'b'不一样; it is trying to use + as a unary operator on the 'b' string, and then make a tuple.它试图在'b'字符串上使用+作为一元运算符,然后创建一个元组。 (You know how you can write eg -1 to get a negative number? The - there is a unary operator . It turns out you can similarly write +1 ; it means the same as 1 , of course.) (你知道如何写例如-1来得到一个负数吗? -有一个一元运算符。事实证明你可以类似地写+1 ;当然,它的含义与1相同。)

If something "is not iterable"如果某些东西“不可迭代”

If you want a for loop to run a specific number of times, you still need something to iterate over;如果你想让for循环运行特定次数,你仍然需要一些东西来迭代; a range is the usual choice. range是通常的选择。 The same is true if you are using a list comprehension etc. to make multiple copies of a value .如果您使用列表理解等来制作 value 的多个副本,情况也是如此。 If you have an integer x and you want to make a list with one item, which is that integer , that is spelled [x] , not list(x) .如果你有一个 integer x并且你想列出一个项目,那就是 integer ,拼写为[x] ,而不是list(x)

If something "is not callable"如果某些东西“不可调用”

If a 'module' object is not callable , it's most likely because you want a function or class from the module, that has the same name as the module, rather than the module itself .如果'module' object is not callable ,这很可能是因为您需要模块中的 function 或 class 而不是模块本身的名称 The linked example is for the socket standard library;链接示例适用于socket标准库; other common cases include datetime and random .其他常见情况包括datetimerandom

Also make sure that you didn't already call a function and remember the result, instead of remembering the function itself .还要确保您尚未调用 function 并记住结果,而不是记住function 本身 This is a common problem with APIs that expect a "callback" function.这是期望“回调”function 的 API 的常见问题。 (If you need to choose the arguments ahead of time, but not actually call the function, see Python Argument Binders .) Sometimes people also try to provide the name of a function as a string , rather than providing the function itself. (If you need to choose the arguments ahead of time, but not actually call the function, see Python Argument Binders .) Sometimes people also try to provide the name of a function as a string , rather than providing the function itself.

If something "is not subscriptable"如果某些东西“不可下标”

One common cause is trying to get "digits" from a number.一个常见的原因是试图从数字中获取“数字”。 int and float values aren't strings; intfloat不是字符串; they don't have digits in them .他们没有数字 The numeric value is the same no matter what base you write them in, and there are other ways to write a number besides base ten;不管你写什么基数,数值都是一样的,除了以十为基数之外,还有其他的写法; so it is your responsibility to create the appropriate string first.因此,您有责任首先创建适当的字符串。

How can I understand and fix the problem?我怎样才能理解和解决问题?

First, look at the traceback to see where in the code the error occurs.首先,查看回溯以查看错误发生在代码中的哪个位置。 If it's in a library, work backwards to the point where your code uses the library.如果它在库中,请向后工作到您的代码使用该库的位置。 Then read the error message carefully, and compare it to the code, to figure out what causes the complaint.然后仔细阅读错误信息,并将其与代码进行比较,找出导致投诉的原因。 Finally, think carefully: is the operation wrong, or the values ?最后,仔细想想:是操作错了,还是价值观错了?

Examples例子

(TODO) (去做)

Some non-obvious things一些不明显的事情

Reusing names重用名称

Did you perhaps reassign the name of a built-in callable , such as str or input or list ?您是否可能重新分配了内置 callable 的名称,例如strinputlist Did you try to reuse a name for two different things (for example, a function and some global data that it uses)?您是否尝试为两个不同的事物重用名称(例如,function 和它使用的一些全局数据)?

Names in Python can only refer to one thing at a time. Python 中的名称一次只能指一件事。 If you use, say, list as a variable name, then it isn't also the name of "the abstract concept of a list" any more, so you can't use it to create more lists (which includes converting other things to lists).例如,如果您使用list作为变量名,那么它不再是“列表的抽象概念”的名称,因此您不能使用它来创建更多列表(包括将其他内容转换为列表)。 If you create a global variable months with a list of strings, and then write a function months , the function replaces the list, and the function's code can't look up the list.如果用字符串列表创建一个全局变量months ,然后写一个function months ,function替换列表,函数的代码无法查找列表。 This can easily happen accidentally when using from some_module import * syntax .使用from some_module import * syntax 时很容易意外发生。

Similarly, if you try to make a class that uses the same name for an method as for a data attribute of the instances , that will cause the same problem.类似地,如果您尝试创建一个 class ,该方法使用与实例的数据属性相同的名称,这将导致相同的问题。 (There's also a tricky special case with @staticmethod ). @staticmethod还有一个棘手的特殊情况)。

Processing lists处理清单

Sometimes people expect to be able to use a list like a Numpy array, and "broadcast" an operation or a function call to each element of the list.有时人们希望能够使用像 Numpy 数组这样的列表,并对列表的每个元素“广播”一个操作function 调用 That doesn't work.那是行不通的。 Use a list comprehension instead .请改用列表推导

Handling None处理None

Consider whether you need to handle None as a special case .考虑是否需要将None作为特殊情况处理 But try to avoid getting into that situation in the first place;但首先要尽量避免陷入这种情况; "special cases aren't special enough to break the rules", as they say.正如他们所说,“特殊情况不足以打破规则”。

Trying to use a library (including a standard library)尝试使用库(包括标准库)

If something doesn't work like you'd expect (for example, trying to subtract datetime.time s or serialize an instance of a user-defined class as JSON ) - rather than trying to treat the problem as a debugging question, search for solutions for what you want that part of the code to do .如果某些事情不像您期望的那样工作(例如,尝试减去datetime.time将用户定义的 class 的实例序列化为 JSON ) - 而不是尝试将问题视为调试问题,搜索您希望这部分代码执行的操作的解决方案。

If the error mentions a 'str' type and you thought it should be a number如果错误提到“str”类型并且您认为它应该是一个数字

Did you get it from the input function?你是从input function 得到的吗? That gives you a str , even if it looks like a number.这给了你一个str ,即使它看起来像一个数字。 Please see How can I read inputs as numbers?请参阅如何将输入读取为数字? . .

If the error mentions a 'function' type or 'type' type如果错误提到“函数”类型或“类型”类型

Did you forget to call the function, or create an instance of a class?您是否忘记调用 function 或创建 class 的实例?


Error messages about wrong arguments关于错误 arguments 的错误消息

The error message will tell you the name of the function;错误信息会告诉你function的名称; so look at the part of the line that calls that function, and check the arguments.因此,请查看调用 function 的行的部分,并检查 arguments。 Is there a correct number of positional arguments?位置 arguments 的数量是否正确? Is there a keyword argument that must be provided, and is missing?是否有必须提供的关键字参数,但缺少? Is there a keyword argument that shouldn't be provided?是否存在不应提供的关键字参数? Is there a positional argument that is also provided by keyword?关键字是否也提供了位置参数?

If you are writing a method for a class, remember to allow for self .如果您正在为 class 编写方法,请记住允许self It is necessary for instance methods.实例方法是必需的。 If you are calling a method, keep in mind that self will be counted as an argument (both for the amount "required" and the amount "given").如果您正在调用一个方法,请记住self将被视为一个参数(“需要”的数量和“给定”的数量)。

If you are using a callback that takes arguments from an indirect source, check the source .如果您使用从间接源获取 arguments 的回调,请检查源

If you are trying to create an instance of your own class, and get an TypeError from __init__ , make sure that you actually wrote an __init__ .如果您尝试创建自己的 class 的实例,并从__init__获取TypeError请确保您确实编写了__init__

If you don't know what the arguments should be, check the documentation .如果您不知道 arguments 应该是什么,请查看文档 If the arguments make sense, maybe the function is wrong - make sure you didn't confuse it for another one in the same library.如果 arguments 有意义,那么function可能是错误的 - 确保您没有将它与同一个库中的另一个混淆。

Error messages about operand types有关操作数类型的错误消息

Make sure the operator is correct for what you want the code to do (for example: ^ is not exponentiation; you want ** ), and then check the operand types.确保运算符对于您希望代码执行的操作是正确的(例如: ^不是求幂;您想要** ),然后检查操作数类型。

In most cases, it will be appropriate to convert the type - but think carefully.在大多数情况下,转换类型是合适的——但请仔细考虑。 Make sure the operation will make sense with the new types.确保操作对新类型有意义。 For example, if the code is l + 'second' , and l is a list that currently contains ['first'] , chances are good we don't want to concatenate strings, but instead create a modified list that also has 'second' as an element.例如,如果代码是l + 'second' ,并且l是一个当前包含['first']list ,那么我们很可能不想连接字符串,而是创建一个也有'second'的修改列表'second'作为一个元素。 So actually we wanted to "add" another list : l + ['second'] .所以实际上我们想“添加”另一个列表l + ['second']

If string indices must be integers , it could be that the string being indexed is JSON or something of that sort, which should have been parsed already to create a dictionary (possibly with nested lists and dictionaries).如果string indices must be integers ,则被索引的字符串可能是 JSON或类似的东西,它们应该已经被解析以创建字典(可能带有嵌套列表和字典)。

Error messages about string formatting有关字符串格式的错误消息

Seriously, did you intend to do string formatting?说真的,您是否打算进行字符串格式化? If you do want to format a string, consider using f-strings or the .format method - these are easier to debug, and have fewer special cases.如果您确实想格式化字符串,请考虑使用 f-strings 或.format方法- 这些更容易调试,并且特殊情况更少。 But more likely, the left-hand side is some string like '1' that should have been converted to int (or maybe float ) first.但更有可能的是,左侧是一些像'1'这样的字符串,应该首先转换为int (或者可能float )。

Error messages about a "descriptor"关于“描述符”的错误消息

Python's error message here is fairly cryptic - it's using terminology that most programmers rarely if ever have to worry about. Python 的错误消息在这里相当神秘——它使用的术语大多数程序员很少会担心。 But once recognized, the error is very easy to pattern-match.但是一旦识别出来,错误就很容易进行模式匹配。 Take special care if the class can be instantiated with no arguments - an empty pair of parentheses () is still necessary to instantiate the class;如果 class 可以在没有 arguments 的情况下实例化,请特别注意 -仍然需要一对空括号()来实例化 class; otherwise, the code refers to the class itself .否则,代码指的是 class 本身 An instance is required in order to use methods.为了使用方法,需要一个实例。

Custom error messages from built-in functions来自内置函数的自定义错误消息

A "bad operand" for a "unary" operator (for example bad operand type for unary +: 'str' ) can be caused by a stray comma . “一元”运算符的“错误操作数”(例如bad operand type for unary +: 'str'可能是由杂散逗号引起的 'a', + 'b' is not the same as 'a' + 'b' ; 'a', + 'b''a' + 'b'不一样; it is trying to use + as a unary operator on the 'b' string, and then make a tuple.它试图在'b'字符串上使用+作为一元运算符,然后创建一个元组。 (You know how you can write eg -1 to get a negative number? The - there is a unary operator . It turns out you can similarly write +1 ; it means the same as 1 , of course.) (你知道如何写例如-1来得到一个负数吗? -有一个一元运算符。事实证明你可以类似地写+1 ;当然,它的含义与1相同。)

Especially if you have had to migrate code from 2.x to 3.x, be very careful about the distinction between bytes and str types in 3.x.特别是如果您必须将代码从 2.x 迁移到 3.x,请非常注意 3.x 中bytesstr类型之间的区别。 bytes represents raw data ; bytes代表原始数据 str represents text . str代表文本 These are fundamentally different and unrelated things, and it is only possible to convert from one to the other by using an encoding .这些是根本不同且不相关的事物,只能通过使用编码从一个转换为另一个。 In Python 3.x, files that are opened in a binary mode (using 'b' in the mode string) produce bytes when read, and must be given something compatible with bytes when written to.在 Python 3.x 中,以二进制模式打开的文件(在模式字符串中使用'b' )在读取时会产生bytes ,并且在写入时必须提供与bytes兼容的内容。 str does not qualify; str不符合条件; you must specify an encoding explicitly.您必须明确指定编码。 The canonical for this problem is TypeError: a bytes-like object is required, not 'str' when writing to a file in Python 3 .这个问题的典型是TypeError: a bytes-like object is required, not 'str' when writing to a file in Python 3

Error messages where something "is not" usable in some way以某种方式“不”可用的错误消息

Not iterable不可迭代

When something is not iterable , the problem is very likely with the thing, rather than the iteration.当某事is not iterable时,问题很可能出在该事物上,而不是迭代。 If you want a for loop to run a specific number of times, you still need something to iterate over;如果你想让for循环运行特定次数,你仍然需要一些东西来迭代; a range is the usual choice. range是通常的选择。 The same is true if you are using a list comprehension etc. to make multiple copies of a value .如果您使用列表理解等来制作 value 的多个副本,情况也是如此。 If you have an integer x and you want to make a list with one item, which is that integer , that is spelled [x] , not list(x) .如果你有一个 integer x并且你想列出一个项目,那就是 integer ,拼写为[x] ,而不是list(x)

Not callable不可调用

If a 'module' object is not callable , it's most likely because you want a function or class from the module, that has the same name as the module, rather than the module itself .如果'module' object is not callable ,这很可能是因为您需要模块中的 function 或 class 而不是模块本身的名称 The linked example is for the socket standard library;链接示例适用于socket标准库; other common cases include datetime and random .其他常见情况包括datetimerandom

Also make sure that the code doesn't call a function and remember the result, instead of remembering the function itself .还要确保代码没有调用 function 并记住结果,而不是记住function 本身 This is a common problem with APIs that expect a "callback" function.这是期望“回调”function 的 API 的常见问题。 (If you need to choose the arguments ahead of time, but not actually call the function, see Python Argument Binders .) Sometimes people also try to provide the name of a function as a string , rather than providing the function itself. (If you need to choose the arguments ahead of time, but not actually call the function, see Python Argument Binders .) Sometimes people also try to provide the name of a function as a string , rather than providing the function itself.

Not subscriptable不可下标

Sometimes, people try to get "digits" from a number by indexing into it as if it were a string.有时,人们试图通过索引数字来从数字中获取“数字”,就好像它是一个字符串一样。 int and float values aren't strings; intfloat不是字符串; they don't have digits in them .他们没有数字 So this will cause a "is not subscriptable" TypeError .所以这将导致“不可下标” TypeError The numeric value is the same no matter what base you write them in, and there are other ways to write a number besides base ten;不管你写什么基数,数值都是一样的,除了以十为基数之外,还有其他的写法; so it is your responsibility to create the appropriate string first.因此,您有责任首先创建适当的字符串。

If you are trying to work with nested lists, be careful about indexing into them.如果您尝试使用嵌套列表,请注意对它们进行索引。 A list like example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] should be indexed like example[i][j] , not eg example[i[j]] .example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]这样的列表应该像example[i][j]那样被索引,而不是example[i[j]] . The logic here should be pretty simple: the correct code means to index into example (getting a list of integers), and then index into that result.这里的逻辑应该很简单:正确的代码意味着对example进行索引(获取整数列表),然后对结果进行索引。 The incorrect code means to use j as an index into i first, because of how the brackets are nested.不正确的代码意味着首先使用j作为i的索引,因为括号是如何嵌套的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我该如何解决这个错误? 值错误和类型错误。 Slider - How can I fix this error? ValueError and TypeError. Slider 我正在尝试使用 BeautifulSoup 获取此网站的标题,但我一直收到 TypeError,我该如何解决? - I'm trying to get the title for this website using BeautifulSoup but I keep getting a TypeError, how do I fix this? 我该如何解决? 我没有得到正确的价值 sarah - how do i fix this? i'm not getting the right value for sarah 我收到一个 IndentationError。 我如何解决它? - I'm getting an IndentationError. How do I fix it? TypeError。 我不明白这是什么错误 - TypeError. I don't understand what the error is 我正在尝试编写一个可以针对 OSINT 数据库扫描 IP 的程序,但我一直遇到 TypeError。 我不确定从这里到哪里去 go - I'm trying to write a program that can scan IPs against OSINT databases, but I keep running into TypeError. I'm not sure where to go from here 基本程序TypeError。 我究竟做错了什么? - Rudimentary program TypeError. What am I doing wrong? 当我尝试使用pip install安装此软件包时,如何解决此错误? - How do I fix this error I'm getting when I try to install this package with pip install? 如何修复 Python 中的“TypeError”? - How do I fix a “TypeError” in Python? 如何修复 Python 中的 TypeError - How do I fix TypeError in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM