标签归档:typeerror

Python TypeError:格式字符串的参数不足

问题:Python TypeError:格式字符串的参数不足

这是输出。我相信这些是utf-8字符串…其中一些可以是NoneType,但是在类似这样的字符串之前会立即失败…

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname, procversion, int(percent), exe, description, company, procurl

TypeError:格式字符串的参数不足

虽然是7比7?

Here’s the output. These are utf-8 strings I believe… some of these can be NoneType but it fails immediately, before ones like that…

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname, procversion, int(percent), exe, description, company, procurl

TypeError: not enough arguments for format string

Its 7 for 7 though?


回答 0

请注意,%格式化字符串的语法已过时。如果您的Python版本支持它,则应编写:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

这也可以修复您碰巧遇到的错误。

Note that the % syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

This also fixes the error that you happened to have.


回答 1

您需要将格式参数放入元组(添加括号):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

您当前拥有的等同于以下内容:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

例:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

回答 2

%在格式字符串中用作百分比字符时,出现了相同的错误。解决的办法是加倍%%

I got the same error when using % as a percent character in my format string. The solution to this is to double up the %%.


Python:TypeError:无法散列的类型:“列表”

问题:Python:TypeError:无法散列的类型:“列表”

我正在尝试拍摄一个看起来像这样的文件

AAA x 111
AAB x 111
AAA x 112
AAC x 123
...

并使用字典使输出看起来像这样

{AAA: ['111', '112'], AAB: ['111'], AAC: [123], ...}

这就是我尝试过的

file = open("filename.txt", "r") 
readline = file.readline().rstrip()
while readline!= "":
    list = []
    list = readline.split(" ")
    j = list.index("x")
    k = list[0:j]
    v = list[j + 1:]
    d = {}
    if k not in d == False:
        d[k] = []
    d[k].append(v)
    readline = file.readline().rstrip()

我不断收到TypeError: unhashable type: 'list'。我知道字典中的键不能是列表,但是我试图将我的值变成列表而不是键。我想知道我是否在某个地方犯了一个错误。

I’m trying to take a file that looks like this:

AAA x 111
AAB x 111
AAA x 112
AAC x 123
...

And use a dictionary to so that the output looks like this

{AAA: ['111', '112'], AAB: ['111'], AAC: [123], ...}

This is what I’ve tried

file = open("filename.txt", "r") 
readline = file.readline().rstrip()
while readline!= "":
    list = []
    list = readline.split(" ")
    j = list.index("x")
    k = list[0:j]
    v = list[j + 1:]
    d = {}
    if k not in d == False:
        d[k] = []
    d[k].append(v)
    readline = file.readline().rstrip()

I keep getting a TypeError: unhashable type: 'list'. I know that keys in a dictionary can’t be lists but I’m trying to make my value into a list not the key. I’m wondering if I made a mistake somewhere.


回答 0

如其他答案所示,错误是由于造成的k = list[0:j],您的密钥被转换为列表。您可以尝试做的一件事是重新编写代码以利用该split功能:

# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
  d = {}
  # Here we use readlines() to split the file into a list where each element is a line
  for line in f.readlines():
    # Now we split the file on `x`, since the part before the x will be
    # the key and the part after the value
    line = line.split('x')
    # Take the line parts and strip out the spaces, assigning them to the variables
    # Once you get a bit more comfortable, this works as well:
    # key, value = [x.strip() for x in line] 
    key = line[0].strip()
    value = line[1].strip()
    # Now we check if the dictionary contains the key; if so, append the new value,
    # and if not, make a new list that contains the current value
    # (For future reference, this is a great place for a defaultdict :)
    if key in d:
      d[key].append(value)
    else:
      d[key] = [value]

print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

请注意,如果您使用的是Python 3.x,则必须稍作调整才能使其正常运行。如果您使用打开文件rb,则需要使用line = line.split(b'x')(确保使用正确的字符串类型分割字节)。您也可以使用with open('filename.txt', 'rU') as f:(甚至with open('filename.txt', 'r') as f:)打开文件,它应该可以正常工作。

As indicated by the other answers, the error is to due to k = list[0:j], where your key is converted to a list. One thing you could try is reworking your code to take advantage of the split function:

# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
  d = {}
  # Here we use readlines() to split the file into a list where each element is a line
  for line in f.readlines():
    # Now we split the file on `x`, since the part before the x will be
    # the key and the part after the value
    line = line.split('x')
    # Take the line parts and strip out the spaces, assigning them to the variables
    # Once you get a bit more comfortable, this works as well:
    # key, value = [x.strip() for x in line] 
    key = line[0].strip()
    value = line[1].strip()
    # Now we check if the dictionary contains the key; if so, append the new value,
    # and if not, make a new list that contains the current value
    # (For future reference, this is a great place for a defaultdict :)
    if key in d:
      d[key].append(value)
    else:
      d[key] = [value]

print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

Note that if you are using Python 3.x, you’ll have to make a minor adjustment to get it work properly. If you open the file with rb, you’ll need to use line = line.split(b'x') (which makes sure you are splitting the byte with the proper type of string). You can also open the file using with open('filename.txt', 'rU') as f: (or even with open('filename.txt', 'r') as f:) and it should work fine.


回答 1

注意: 此答案未明确回答所提问题。其他答案可以做到。由于问题是特定于场景的,提出的异常是一般的,因此此答案指向一般情况。

哈希值只是整数,用于在字典查找期间快速比较字典关键字。

在内部,hash()方法调用__hash__()对象的方法,该方法默认为任何对象设置。

嵌套列表转换为集合

>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

发生这种情况是因为列表内的列表是不能散列的列表。可以通过将内部嵌套列表转换为元组来解决,

>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])

显式哈希嵌套列表

>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506

避免此错误的解决方案是将列表重组为具有嵌套元组而不是列表。

Note: This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.

Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.

Internally, hash() method calls __hash__() method of an object which are set by default for any object.

Converting a nested list to a set

>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,

>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])

Explicitly hashing a nested list

>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506

The solution to avoid this error is to restructure the list to have nested tuples instead of lists.


回答 2

您正在尝试使用k(这是一个列表)作为的键d。列表是可变的,不能用作字典键。

另外,由于这一行,您永远不会初始化字典中的列表:

if k not in d == False:

应该是:

if k not in d == True:

实际上应该是:

if k not in d:

You’re trying to use k (which is a list) as a key for d. Lists are mutable and can’t be used as dict keys.

Also, you’re never initializing the lists in the dictionary, because of this line:

if k not in d == False:

Which should be:

if k not in d == True:

Which should actually be:

if k not in d:

回答 3

之所以会出现unhashable type: 'list'异常,是因为k = list[0:j]将其设置k为列表的“切片”,从逻辑上讲,它是另一个(通常较短的)列表。您需要的只是获得列表中的第一项,这样写k = list[0]。对于的调用返回的列表的第三个元素v = list[j + 1:]应该是相同的。v = list[2]readline.split(" ")

我注意到了代码的其他一些可能的问题,我将提及其中的一些问题。一个大的一个是你不希望(重新)初始化dd = {}每一行的循环中读取。另一个是,将变量命名为任何内置类型通常不是一个好主意,因为它会阻止您在需要时访问其中一个变量,并且会使习惯于该变量的其他人感到困惑。指定这些标准项目之一的名称。因此,您应该将变量list变量重命名为其他名称,以避免类似的问题。

这是您的工作版本,其中进行了这些更改,我还简化了if您拥有的语句表达式,该语句表达式可检查键是否已在字典中-甚至有更短的隐式方法来执行此类操作,但使用条件语句声明目前还不错。

d = {}
file = open("filename.txt", "r")
readline = file.readline().rstrip()
while readline:
    lst = readline.split(" ") # Split into sequence like ['AAA', 'x', '111'].
    k = lst[0]  # First item.
    v = lst[2]  # Third item.
    if k not in d:  # New key?
        d[k] = []  # Initialize its associated value to an empty list.
    d[k].append(v)
    readline = file.readline().rstrip()

file.close()  # Done reading file.
print('d: {}'.format(d))

输出:

d: {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

The reason you’re getting the unhashable type: 'list' exception is because k = list[0:j] sets k to be a “slice” of the list, which is logically another, often shorter, list. What you need is to get just the first item in list, written like so k = list[0]. The same for v = list[j + 1:] which should just be v = list[2] for the third element of the list returned from the call to readline.split(" ").

I noticed several other likely problems with the code, of which I’ll mention a few. A big one is you don’t want to (re)initialize d with d = {} for each line read in the loop. Another is it’s generally not a good idea to name variables the same as any of the built-ins types because it’ll prevent you from being able to access one of them if you need it — and it’s confusing to others who are used to the names designating one of these standard items. For that reason, you ought to rename your variable list variable something different to avoid issues like that.

Here’s a working version of your with these changes in it, I also replaced the if statement expression you used to check to see if the key was already in the dictionary and now make use of a dictionary’s setdefault() method to accomplish the same thing a little more succinctly.

d = {}
with open("nameerror.txt", "r") as file:
    line = file.readline().rstrip()
    while line:
        lst = line.split() # Split into sequence like ['AAA', 'x', '111'].
        k, _, v = lst[:3]  # Get first and third items.
        d.setdefault(k, []).append(v)
        line = file.readline().rstrip()

print('d: {}'.format(d))

Output:

d: {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

回答 4

之所以TypeError会发生,k是因为是一个列表,因为它是使用另一个带有line的列表中的一个切片创建的k = list[0:j]。这可能类似于k = ' '.join(list[0:j]),因此您需要一个字符串。

除此之外,if正如Jesse的回答所指出的那样,您的陈述不正确,应该读为if k not in dif not k in d(我更喜欢后者)。

您还需要d = {}for循环中清除字典,因为每次迭代都在其中。

请注意,您也不应使用listfile作为变量名,因为您将掩盖内建函数。

这是我重写代码的方法:

d = {}
with open("filename.txt", "r") as input_file:
    for line in input_file:
        fields = line.split()
        j = fields.index("x")
        k = " ".join(fields[:j])
        d.setdefault(k, []).append(" ".join(fields[j+1:]))

dict.setdefault()上面的方法替换了if k not in d代码中的逻辑。

The TypeError is happening because k is a list, since it is created using a slice from another list with the line k = list[0:j]. This should probably be something like k = ' '.join(list[0:j]), so you have a string instead.

In addition to this, your if statement is incorrect as noted by Jesse’s answer, which should read if k not in d or if not k in d (I prefer the latter).

You are also clearing your dictionary on each iteration since you have d = {} inside of your for loop.

Note that you should also not be using list or file as variable names, since you will be masking builtins.

Here is how I would rewrite your code:

d = {}
with open("filename.txt", "r") as input_file:
    for line in input_file:
        fields = line.split()
        j = fields.index("x")
        k = " ".join(fields[:j])
        d.setdefault(k, []).append(" ".join(fields[j+1:]))

The dict.setdefault() method above replaces the if k not in d logic from your code.


回答 5

    python 3.2

    with open("d://test.txt") as f:
              k=(((i.split("\n"))[0].rstrip()).split() for i in f.readlines())
              d={}
              for i,_,v in k:
                      d.setdefault(i,[]).append(v)
    python 3.2

    with open("d://test.txt") as f:
              k=(((i.split("\n"))[0].rstrip()).split() for i in f.readlines())
              d={}
              for i,_,v in k:
                      d.setdefault(i,[]).append(v)

在Python中序列化JSON时,“ TypeError :(整数)不可JSON序列化”?

问题:在Python中序列化JSON时,“ TypeError :(整数)不可JSON序列化”?

我正在尝试从python发送一个简单的字典到json文件,但是我一直收到“ TypeError:1425不能序列化JSON”消息。

import json
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8'))
afile.close()

如果我添加默认参数,则它将写入,但是整数值将作为字符串写入json文件,这是不可取的。

afile.write(json.dumps(alerts,encoding='UTF-8',default=str))

I am trying to send a simple dictionary to a json file from python, but I keep getting the “TypeError: 1425 is not JSON serializable” message.

import json
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8'))
afile.close()

If I add the default argument, then it writes, but the integer values are written to the json file as strings, which is undesirable.

afile.write(json.dumps(alerts,encoding='UTF-8',default=str))

回答 0

我发现了问题。问题是我的整数实际上是type numpy.int64

I found my problem. The issue was that my integers were actually type numpy.int64.


回答 1

在python 3中将numpy.int64转储到json字符串中似乎存在问题,并且python团队已经对此进行了讨论。可以在此处找到更多详细信息。

Serhiy Storchaka提供了一种解决方法。它工作得很好,所以我将其粘贴在这里:

def convert(o):
    if isinstance(o, numpy.int64): return int(o)  
    raise TypeError

json.dumps({'value': numpy.int64(42)}, default=convert)

It seems like there may be a issue to dump numpy.int64 into json string in Python 3 and the python team already have a conversation about it. More details can be found here.

There is a workaround provided by Serhiy Storchaka. It works very well so I paste it here:

def convert(o):
    if isinstance(o, numpy.int64): return int(o)  
    raise TypeError

json.dumps({'value': numpy.int64(42)}, default=convert)

回答 2

这为我解决了问题:

def serialize(self):
    return {
        my_int: int(self.my_int), 
        my_float: float(self.my_float)
    }

This solved the problem for me:

def serialize(self):
    return {
        my_int: int(self.my_int), 
        my_float: float(self.my_float)
    }

回答 3

只需将数字从int64(从numpy)转换为int

例如,如果变量x是int64:

int(x)

如果是int64数组:

map(int, x)

Just convert numbers from int64 (from numpy) to int.

For example, if variable x is a int64:

int(x)

If is array of int64:

map(int, x)

回答 4

正如@JAC在评价最高的答案的注释中指出的那样,可以在将numpy dtypes转换为本地python类型的线程中找到通用解决方案(适用于所有numpy类型) 。

不过,我将在下面添加解决方案的版本,因为我需要一个通用的解决方案,该解决方案将这些答案以及其他线程的答案结合在一起。这应该适用于几乎所有的numpy类型。

def convert(o):
    if isinstance(o, np.generic): return o.item()  
    raise TypeError

json.dumps({'value': numpy.int64(42)}, default=convert)

as @JAC pointed out in the comments of the highest rated answer, the generic solution (for all numpy types) can be found in the thread Converting numpy dtypes to native python types.

Nevertheless, I´ll add my version of the solution below, as my in my case I needed a generic solution that combines these answers and with the answers of the other thread. This should work with almost all numpy types.

def convert(o):
    if isinstance(o, np.generic): return o.item()  
    raise TypeError

json.dumps({'value': numpy.int64(42)}, default=convert)

回答 5

这可能是较晚的响应,但最近我遇到了相同的错误。经过大量的冲浪后,此解决方案对我有所帮助。

alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
def myconverter(obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, datetime.datetime):
            return obj.__str__()

通话myconverterjson.dumps()像下面。json.dumps(alerts, default=myconverter).

This might be the late response, but recently i got the same error. After lot of surfing this solution helped me.

alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
def myconverter(obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, datetime.datetime):
            return obj.__str__()

Call myconverter in json.dumps() like below. json.dumps(alerts, default=myconverter).


回答 6

或者,您可以先将对象转换为数据框:

df = pd.DataFrame(obj)

然后将其保存dataframejson文件中:

df.to_json(path_or_buf='df.json')

希望这可以帮助

Alternatively you can convert your object into a dataframe first:

df = pd.DataFrame(obj)

and then save this dataframe in a json file:

df.to_json(path_or_buf='df.json')

Hope this helps


回答 7

您具有Numpy数据类型,只需更改为普通的int()或float()数据类型即可。它将正常工作。

You have Numpy Data Type, Just change to normal int() or float() data type. it will work fine.


回答 8

同样的问题。列出包含numpy.int64类型的数字,该数字引发TypeError。我的快速解决方法是

mylist = eval(str(mylist_of_integers))
json.dumps({'mylist': mylist})

它将列表转换为str(),而eval()函数像python表达式那样评估“字符串”,并在我的情况下以整数列表形式返回结果。

Same problem. List contained numbers of type numpy.int64 which throws a TypeError. Quick workaround for me was to

mylist = eval(str(mylist_of_integers))
json.dumps({'mylist': mylist})

which converts list to str() and eval() function evaluates the String like a Python expression and returns the result as a list of integers in my case.


回答 9

from numpyencoder import NumpyEncoder

在Python3中解决此问题:

import json
from numpyencoder import NumpyEncoder
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 
15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8',cls=NumpyEncoder))
afile.close()

Use the below code to resolve the issue.

import json
from numpyencoder import NumpyEncoder
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 
15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8',cls=NumpyEncoder))
afile.close()

TypeError:module .__ init __()最多接受2个参数(给定3个)

问题:TypeError:module .__ init __()最多接受2个参数(给定3个)

我在名为的文件中定义了一个类Object.py。当我尝试从另一个文件中的此类继承时,调用构造函数将引发异常:

TypeError: module.__init__() takes at most 2 arguments (3 given)

这是我的代码:

import Object

class Visitor(Object):
    pass

instance = Visitor()  # this line throws the exception

我究竟做错了什么?

I have defined a class in a file named Object.py. When I try to inherit from this class in another file, calling the constructor throws an exception:

TypeError: module.__init__() takes at most 2 arguments (3 given)

This is my code:

import Object

class Visitor(Object):
    pass

instance = Visitor()  # this line throws the exception

What am I doing wrong?


回答 0

发生错误是因为Object是模块,而不是类。因此,您的继承权很严格。

将您的导入语句更改为:

from Object import ClassName

和您的类定义为:

class Visitor(ClassName):

要么

将您的类定义更改为:

class Visitor(Object.ClassName):
   etc

Your error is happening because Object is a module, not a class. So your inheritance is screwy.

Change your import statement to:

from Object import ClassName

and your class definition to:

class Visitor(ClassName):

or

change your class definition to:

class Visitor(Object.ClassName):
   etc

回答 1

即使在@Mickey Perlstein的回答和他3个小时的侦探工作之后,我仍然花了几分钟才将其应用于我自己的烂摊子。如果有人像我一样需要更多帮助,这就是我的处境。

  • 响应是一个模块
  • 响应是响应模块中的基类
  • GeoJsonResponse是从Response派生的新类

初始GeoJsonResponse类:

from pyexample.responses import Response

class GeoJsonResponse(Response):

    def __init__(self, geo_json_data):

看起来不错 在尝试调试事物之前,没有问题,这是当您收到一堆看似模糊的错误消息时,如下所示:

从pyexample.responses中导入GeoJsonResponse .. \ pyexample \ responses \ GeoJsonResponse.py:12:在(模块)类GeoJsonResponse(Response)中:

E TypeError:module()最多接受2个参数(给定3个)

==================================错误=============== ======================

___________________收集测试错误/test_geojson.py ____________________

pyexample.responses中的test_geojson.py:2:在(模块)中导入GeoJsonResponse .. \ pyexample \ responses \ GeoJsonResponse.py:12:在(模块)中

class GeoJsonResponse(Response):E TypeError:module()最多接受2个参数(给定3个)

错误:找不到:\ PyExample \ tests \ test_geojson.py :: TestGeoJson :: test_api_response

C:\ Python37 \ lib \ site-packages \ aenum__init __。py:163

(在[]中的任何一个都没有名称’PyExample \ tests \ test_geojson.py :: TestGeoJson :: test_api_response’)

错误尽了最大的努力,向我指出了正确的方向,@ Mickey Perlstein的回答仍然无效,花了我一分钟时间,将所有内容整合到我自己的上下文中:

我正在导入模块

from pyexample.responses import Response

当我应该导入该类时

from pyexample.responses.Response import Response

希望这对某人有帮助。(以我的辩护,还为时过早。)

Even after @Mickey Perlstein’s answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here’s what was going on in my situation.

  • responses is a module
  • Response is a base class within the responses module
  • GeoJsonResponse is a new class derived from Response

Initial GeoJsonResponse class:

from pyexample.responses import Response

class GeoJsonResponse(Response):

    def __init__(self, geo_json_data):

Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:

from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):

E TypeError: module() takes at most 2 arguments (3 given)

=================================== ERRORS ====================================

___________________ ERROR collecting tests/test_geojson.py ____________________

test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)

class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)

ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response

C:\Python37\lib\site-packages\aenum__init__.py:163

(no name ‘PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response’ in any of [])

The errors were doing their best to point me in the right direction, and @Mickey Perlstein’s answer was dead on, it just took me a minute to put it all together in my own context:

I was importing the module:

from pyexample.responses import Response

when I should have been importing the class:

from pyexample.responses.Response import Response

Hope this helps someone. (In my defense, it’s still pretty early.)


回答 2

您也可以在Python 3.6.1中执行以下操作

from Object import Object as Parent

和您的类定义为:

class Visitor(Parent):

You may also do the following in Python 3.6.1

from Object import Object as Parent

and your class definition to:

class Visitor(Parent):

回答 3

from Object import Object

要么

From Class_Name import Class_name

如果Object是.py文件。

from Object import Object

or

From Class_Name import Class_name

If Object is a .py file.


回答 4

在我遇到问题的情况下,当我尝试扩展类时,我指的是模块。

import logging
class UserdefinedLogging(logging):

如果查看文档信息,您将看到“日志记录”显示为模块。

在这种特定情况下,我必须简单地继承日志记录模块才能为日志记录创建一个额外的类。

In my case where I had the problem I was referring to a module when I tried extending the class.

import logging
class UserdefinedLogging(logging):

If you look at the Documentation Info, you’ll see “logging” displayed as module.

In this specific case I had to simply inherit the logging module to create an extra class for the logging.


TypeError:并非在字符串格式化python期间转换所有参数

问题:TypeError:并非在字符串格式化python期间转换所有参数

该程序应采用两个名称,如果它们的长度相同,则应检查它们是否相同。如果是相同的单词,则将显示“名称相同”。如果它们的长度相同但字母不同,则会显示“名称不同但长度相同”。我有问题的部分在底部的4行中。

#!/usr/bin/env python
# Enter your code for "What's In (The Length Of) A Name?" here.
name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
    if len(name1) > len(name2):
        print ("'{0}' is longer than '{1}'"% name1, name2)
    elif len(name1) < len(name2):
        print ("'{0}'is longer than '{1}'"% name2, name1)

当我运行此代码时,它显示:

Traceback (most recent call last):
  File "program.py", line 13, in <module>
    print ("'{0}' is longer than '{1}'"% name1, name2)
TypeError: not all arguments converted during string formatting

任何建议,高度赞赏。

The program is supposed to take in two names, and if they are the same length it should check if they are the same word. If it’s the same word it will print “The names are the same”. If they are the same length but with different letters it will print “The names are different but the same length”. The part I’m having a problem with is in the bottom 4 lines.

#!/usr/bin/env python
# Enter your code for "What's In (The Length Of) A Name?" here.
name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
    if len(name1) > len(name2):
        print ("'{0}' is longer than '{1}'"% name1, name2)
    elif len(name1) < len(name2):
        print ("'{0}'is longer than '{1}'"% name2, name1)

When I run this code it displays:

Traceback (most recent call last):
  File "program.py", line 13, in <module>
    print ("'{0}' is longer than '{1}'"% name1, name2)
TypeError: not all arguments converted during string formatting

Any suggestions are highly appreciated.


回答 0

您正在混合使用不同的格式功能。

旧式%格式化使用%代码进行格式化:

'It will cost $%d dollars.' % 95

新型{}格式使用{}代码和.format方法

'It will cost ${0} dollars.'.format(95)

请注意,使用旧格式时,必须使用元组指定多个参数:

'%d days and %d nights' % (40, 40)

就您而言,由于您使用的是{}格式说明符,请使用.format

"'{0}' is longer than '{1}'".format(name1, name2)

You’re mixing different format functions.

The old-style % formatting uses % codes for formatting:

'It will cost $%d dollars.' % 95

The new-style {} formatting uses {} codes and the .format method

'It will cost ${0} dollars.'.format(95)

Note that with old-style formatting, you have to specify multiple arguments using a tuple:

'%d days and %d nights' % (40, 40)

In your case, since you’re using {} format specifiers, use .format:

"'{0}' is longer than '{1}'".format(name1, name2)

回答 1

错误在于您的字符串格式。

使用’%’运算符使用传统字符串格式的正确方法是使用printf样式的格式字符串(此处的Python文档:http : //docs.python.org/2/library/string.html#format-字符串语法):

"'%s' is longer than '%s'" % (name1, name2)

但是,’%’运算符将来可能会被弃用。新的PEP 3101做事方式是这样的:

"'{0}' is longer than '{1}'".format(name1, name2)

The error is in your string formatting.

The correct way to use traditional string formatting using the ‘%’ operator is to use a printf-style format string (Python documentation for this here: http://docs.python.org/2/library/string.html#format-string-syntax):

"'%s' is longer than '%s'" % (name1, name2)

However, the ‘%’ operator will probably be deprecated in the future. The new PEP 3101 way of doing things is like this:

"'{0}' is longer than '{1}'".format(name1, name2)

回答 2

对我来说,此错误是在我试图将元组传递给字符串格式方法时引起的。

我从这个问题/答案中找到了解决方案

从链接中复制并粘贴正确答案(“不做我的工作”)

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

用感兴趣的元组作为唯一项(即(tutuple)部分)制作单例元组是这里的关键。

For me, This error was caused when I was attempting to pass in a tuple into the string format method.

I found the solution from this question/answer

Copying and pasting the correct answer from the link (NOT MY WORK):

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.


回答 3

就我而言,这是因为我只需要一个%s,我就缺少值输入。

In my case, it’s because I need only a single %s, i missing values input.


回答 4

除了其他两个答案,我认为缩进在最后两个条件下也是不正确的。条件是一个名字要长于另一个名字,并且它们必须以“ elif”开头且没有缩进。如果将其放在第一个条件下(通过从边缘开始给它四个缩进),则最终会导致矛盾,因为名称的长度不能同时相等且不同。

    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))

In addition to the other two answers, I think the indentations are also incorrect in the last two conditions. The conditions are that one name is longer than the other and they need to start with ‘elif’ and with no indentations. If you put it within the first condition (by giving it four indentations from the margin), it ends up being contradictory because the lengths of the names cannot be equal and different at the same time.

    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))

回答 5

其他一些答案中也指出了很多问题。

  1. 正如nneonneo所指出的,您正在混合使用不同的字符串格式化方法。
  2. 正如GuyP指出的那样,您的缩进也已关闭。

我既提供了.format的示例,也提供了将元组传递给%s的参数说明符的方法。在这两种情况下,缩进均已固定,因此长度匹配时大于/小于检查范围。也将随后的if语句更改为elif,以便仅在先前的同一级别语句为False时才运行。

使用.format进行字符串格式化

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))
elif len(name1) < len(name2):
    print ("{0} is longer than {1}".format(name2, name1))

使用%s和元组进行字符串格式化

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("%s is longer than %s" % (name1, name2))
elif len(name1) < len(name2):
    print ("%s is longer than %s" % (name2, name1))

There is a combination of issues as pointed out in a few of the other answers.

  1. As pointed out by nneonneo you are mixing different String Formatting methods.
  2. As pointed out by GuyP your indentation is off as well.

I’ve provided both the example of .format as well as passing tuples to the argument specifier of %s. In both cases the indentation has been fixed so greater/less than checks are outside of when length matches. Also changed subsequent if statements to elif’s so they only run if the prior same level statement was False.

String Formatting with .format

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))
elif len(name1) < len(name2):
    print ("{0} is longer than {1}".format(name2, name1))

String Formatting with %s and a tuple

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("%s is longer than %s" % (name1, name2))
elif len(name1) < len(name2):
    print ("%s is longer than %s" % (name2, name1))

回答 6

在python 3.7及更高版本中,有一种新的简便方法。语法如下:

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."

输出:

Hello, Eric. You are 74.

In python 3.7 and above there is a new and easy way. here is the syntax:

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."

OutPut:

Hello, Eric. You are 74.

回答 7

我也遇到错误

_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting 

但是列表参数工作良好。

我使用mysqlclient python lib。lib似乎不接受元组args。像这样传递列表参数['arg1', 'arg2'] 将起作用。

I encounter the error as well,

_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting 

But list args work well.

I use mysqlclient python lib. The lib looks like not to accept tuple args. To pass list args like ['arg1', 'arg2'] will work.


回答 8

Django原始SQL查询视图

"SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to)

models.py

class VehicleDamage(models.Model):
    requestdate = models.DateTimeField("requestdate")
    vendor_name = models.CharField("vendor_name", max_length=50)
    class Meta:
        managed=False

views.py

def location_damageReports(request):
    #static date for testing
    date_from = '2019-11-01'
    date_to = '2019-21-01'
    vehicle_damage_reports = VehicleDamage.objects.raw("SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to))
    damage_report = DashboardDamageReportSerializer(vehicle_damage_reports, many=True)
    data={"data": damage_report.data}
    return HttpResponse(json.dumps(data), content_type="application/json")

注意:使用python 3.5和Django 1.11

django raw sql query in view

"SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to)

models.py

class VehicleDamage(models.Model):
    requestdate = models.DateTimeField("requestdate")
    vendor_name = models.CharField("vendor_name", max_length=50)
    class Meta:
        managed=False

views.py

def location_damageReports(request):
    #static date for testing
    date_from = '2019-11-01'
    date_to = '2019-21-01'
    vehicle_damage_reports = VehicleDamage.objects.raw("SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to))
    damage_report = DashboardDamageReportSerializer(vehicle_damage_reports, many=True)
    data={"data": damage_report.data}
    return HttpResponse(json.dumps(data), content_type="application/json")

Note: using python 3.5 and django 1.11


回答 9

对我来说,因为我在一个打印调用中存储了许多值,所以解决方案是创建一个单独的变量以将数据存储为元组,然后调用打印函数。

x = (f"{id}", f"{name}", f"{age}")
print(x) 

For me, as I was storing many values within a single print call, the solution was to create a separate variable to store the data as a tuple and then call the print function.

x = (f"{id}", f"{name}", f"{age}")
print(x) 

对于新样式的类,super()引发“ TypeError:必须为类型,而不是classobj”

问题:对于新样式的类,super()引发“ TypeError:必须为类型,而不是classobj”

以下用法super()引发TypeError:为什么?

>>> from  HTMLParser import HTMLParser
>>> class TextParser(HTMLParser):
...     def __init__(self):
...         super(TextParser, self).__init__()
...         self.all_data = []
...         
>>> TextParser()
(...)
TypeError: must be type, not classobj

在StackOverflow上有一个类似的问题:Python super()引发TypeError,该错误由用户类不是新型类的事实来解释。但是,上面的类是一种新式的类,因为它继承自object

>>> isinstance(HTMLParser(), object)
True

我想念什么?我如何super()在这里使用?

使用HTMLParser.__init__(self)代替super(TextParser, self).__init__()可以工作,但是我想了解TypeError。

PS:Joachim指出,成为一个新类实例并不等同于成为一个实例object。我读了很多相反的书,因此感到困惑(基于object实例测试的新型类实例测试的示例:https : //stackoverflow.com/revisions/2655651/3)。

The following use of super() raises a TypeError: why?

>>> from  HTMLParser import HTMLParser
>>> class TextParser(HTMLParser):
...     def __init__(self):
...         super(TextParser, self).__init__()
...         self.all_data = []
...         
>>> TextParser()
(...)
TypeError: must be type, not classobj

There is a similar question on StackOverflow: Python super() raises TypeError, where the error is explained by the fact that the user class is not a new-style class. However, the class above is a new-style class, as it inherits from object:

>>> isinstance(HTMLParser(), object)
True

What am I missing? How can I use super(), here?

Using HTMLParser.__init__(self) instead of super(TextParser, self).__init__() would work, but I would like to understand the TypeError.

PS: Joachim pointed out that being a new-style-class instance is not equivalent to being an object. I read the opposite many times, hence my confusion (example of new-style class instance test based on object instance test: https://stackoverflow.com/revisions/2655651/3).


回答 0

好吧,这是通常的“ super()不能与老式类一起使用”。

但是,重要的一点是对“这是一个新的实例(即对象)吗?” 的正确测试。是

>>> class OldStyle: pass
>>> instance = OldStyle()
>>> issubclass(instance.__class__, object)
False

而不是(如问题所示):

>>> isinstance(instance, object)
True

对于,正确的“这是新型类”测试是:

>>> issubclass(OldStyle, object)  # OldStyle is not a new-style class
False
>>> issubclass(int, object)  # int is a new-style class
True

关键的一点是,与老式类的的实例和它的类型是不同的。在这里,OldStyle().__class__is OldStyle,它不继承自object,而type(OldStyle())is instance类型,它确实继承自object。基本上,旧式类仅创建类型的对象instance(而新式类将创建类型为类本身的对象)。这大概就是为什么实例OldStyle()object:其type()从继承object(事实上,它的类并没有继承object不计数:老式类只是构建类型的新对象instance)。部分参考:https://stackoverflow.com/a/9699961/42973

PS:新式类和旧式类之间的区别还可以通过以下方式看到:

>>> type(OldStyle)  # OldStyle creates objects but is not itself a type
classobj
>>> isinstance(OldStyle, type)
False
>>> type(int)  # A new-style class is a type
type

(旧式类不是类型,因此它们不能是其实例的类型)。

Alright, it’s the usual “super() cannot be used with an old-style class”.

However, the important point is that the correct test for “is this a new-style instance (i.e. object)?” is

>>> class OldStyle: pass
>>> instance = OldStyle()
>>> issubclass(instance.__class__, object)
False

and not (as in the question):

>>> isinstance(instance, object)
True

For classes, the correct “is this a new-style class” test is:

>>> issubclass(OldStyle, object)  # OldStyle is not a new-style class
False
>>> issubclass(int, object)  # int is a new-style class
True

The crucial point is that with old-style classes, the class of an instance and its type are distinct. Here, OldStyle().__class__ is OldStyle, which does not inherit from object, while type(OldStyle()) is the instance type, which does inherit from object. Basically, an old-style class just creates objects of type instance (whereas a new-style class creates objects whose type is the class itself). This is probably why the instance OldStyle() is an object: its type() inherits from object (the fact that its class does not inherit from object does not count: old-style classes merely construct new objects of type instance). Partial reference: https://stackoverflow.com/a/9699961/42973.

PS: The difference between a new-style class and an old-style one can also be seen with:

>>> type(OldStyle)  # OldStyle creates objects but is not itself a type
classobj
>>> isinstance(OldStyle, type)
False
>>> type(int)  # A new-style class is a type
type

(old-style classes are not types, so they cannot be the type of their instances).


回答 1

super()仅可用于新型类,这意味着根类需要从’object’类继承。

例如,顶级类需要像这样:

class SomeClass(object):
    def __init__(self):
        ....

class SomeClass():
    def __init__(self):
        ....

因此,解决方案是直接调用父级的init方法,如下所示:

class TextParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.all_data = []

super() can be used only in the new-style classes, which means the root class needs to inherit from the ‘object’ class.

For example, the top class need to be like this:

class SomeClass(object):
    def __init__(self):
        ....

not

class SomeClass():
    def __init__(self):
        ....

So, the solution is that call the parent’s init method directly, like this way:

class TextParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.all_data = []

回答 2

您也可以使用class TextParser(HTMLParser, object):。这将创建TextParser一个新样式的类,并且super()可以使用。

You can also use class TextParser(HTMLParser, object):. This makes TextParser a new-style class, and super() can be used.


回答 3

问题是super需要object一个祖先:

>>> class oldstyle:
...     def __init__(self): self.os = True

>>> class myclass(oldstyle):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass()
TypeError: must be type, not classobj

经过仔细检查,发现:

>>> type(myclass)
classobj

但:

>>> class newstyle(object): pass

>>> type(newstyle)
type    

因此,解决您的问题的方法是从对象以及HTMLParser继承。但是确保对象在MRO类中排在最后:

>>> class myclass(oldstyle, object):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass().os
True

The problem is that super needs an object as an ancestor:

>>> class oldstyle:
...     def __init__(self): self.os = True

>>> class myclass(oldstyle):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass()
TypeError: must be type, not classobj

On closer examination one finds:

>>> type(myclass)
classobj

But:

>>> class newstyle(object): pass

>>> type(newstyle)
type    

So the solution to your problem would be to inherit from object as well as from HTMLParser. But make sure object comes last in the classes MRO:

>>> class myclass(oldstyle, object):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass().os
True

回答 4

如果您查看继承树(在2.6版中),则HTMLParser继承自SGMLParser,继承自ParserBase而不继承自object。即HTMLParser是一个老式的类。

关于您的检查isinstance,我在ipython中进行了快速测试:

在[1]中:A类:
   ...:通过
   ...: 

在[2]中:isinstance(A,object)
出[2]:是

即使一个类是老式类,它仍然是的一个实例object

If you look at the inheritance tree (in version 2.6), HTMLParser inherits from SGMLParser which inherits from ParserBase which doesn’t inherits from object. I.e. HTMLParser is an old-style class.

About your checking with isinstance, I did a quick test in ipython:

In [1]: class A:
   ...:     pass
   ...: 

In [2]: isinstance(A, object)
Out[2]: True

Even if a class is old-style class, it’s still an instance of object.


回答 5

正确的方法是在不继承自’object’的旧类中执行以下操作

class A:
    def foo(self):
        return "Hi there"

class B(A):
    def foo(self, name):
        return A.foo(self) + name

the correct way to do will be as following in the old-style classes which doesn’t inherit from ‘object’

class A:
    def foo(self):
        return "Hi there"

class B(A):
    def foo(self, name):
        return A.foo(self) + name

回答 6

FWIW,尽管我不是Python专家,但我对此很满意

>>> class TextParser(HTMLParser):
...    def handle_starttag(self, tag, attrs):
...        if tag == "b":
...            self.all_data.append("bold")
...        else:
...            self.all_data.append("other")
...     
...         
>>> p = TextParser()
>>> p.all_data = []
>>> p.feed(text)
>>> print p.all_data
(...)

只是让我根据需要返回解析结果。

FWIW and though I’m no Python guru I got by with this

>>> class TextParser(HTMLParser):
...    def handle_starttag(self, tag, attrs):
...        if tag == "b":
...            self.all_data.append("bold")
...        else:
...            self.all_data.append("other")
...     
...         
>>> p = TextParser()
>>> p.all_data = []
>>> p.feed(text)
>>> print p.all_data
(...)

Just got me the parse results back as needed.