【问题标题】:count items in an object python计算对象python中的项目
【发布时间】:2017-06-25 10:24:51
【问题描述】:

当我打印我得到的对象时: {'ip': 'ip', 'ip1': 'hi'}

但如果我尝试打印我得到的长度:

Traceback (most recent call last):
    print len(options)
AttributeError: Values instance has no attribute '__len__'

我只需要知道该对象中有多少项目(这似乎只是一本字典)。

这是整个代码:

#!/usr/bin/python

from inspect import getmembers
from optparse import OptionParser



parser = OptionParser()
parser.add_option('-a', '--allow',
    action="store", dest="ip",
    help="query string", default="spam")

parser.add_option('-d', '--deny',
    action="store", dest="ip1",
    help="query string", default="spam")


options, args = parser.parse_args()

print 'Query string:', options.ip
print 'Query string:', options.ip1

count=0
for i in options:
  count+=1
print count

if 1:
  print "Max number of options 1"
  exit

【问题讨论】:

  • 投了反对票,因为您忘记添加对我们调试有用的相关代码。
  • options 似乎是某个 Values 类的实例,该类尚未实现 __len__ 方法。

标签: python


【解决方案1】:

options 不是字典。它是一个Values 对象,它是parse_args() 方法的返回值的组成部分之一。

在上面的代码示例中,请注意您如何使用options.ip 而不是options['ip']。因此,看起来像 dict 键的内容被存储为对象 options 的实例变量。因此,可以使用vars() 函数将它们作为字典检索:

d = vars(options)
print len(d)

如果您查看source,您会发现Values 类没有实现__len__,但它确实实现了__str__

def __str__(self):
    return str(self.__dict__)

(链接源中的第 843-844 行)

这是您使用print options 时看到的内容,而__dict__vars() 函数返回的内容。

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 2023-03-21
    • 2011-11-27
    • 1970-01-01
    相关资源
    最近更新 更多