简体   繁体   English

AttributeError:“设置”对象没有属性“ b”

[英]AttributeError: 'set' object has no attribute 'b'

I have the following code: 我有以下代码:

N1 = int(input())
a = set(list(map(int, input().split())))
N2 = int(input())
for i in range(N2):
    b = input().split()
    c = set(list(map(int, input().split())))
    a.b[0](c)
print(sum(a))

With typical input, the list b looks like this: 使用典型的输入,列表b如下所示:

b = ['intersection_update', '10']

What is the issue with ab[0](c) ? ab[0](c)什么问题? Apparently I am not evaluating it correctly. 显然我没有正确评估它。

The concept seems fine, but it seems like set a is not able to take an attribute which is actually an element of a list. 这个概念似乎很好,但似乎set a无法采用实际上是列表元素的属性。

what I want to evaluate is: 我要评估的是:

a.intersection_update(c)

Here's the error I get: 这是我得到的错误:

Traceback (most recent call last):
  File "solution.py", line 7, in 
    a.b[0](c)
AttributeError: 'set' object has no attribute 'b'

I think you want to use getattr , to get an attribute who's name stored as a string in another variable: 我认为您想使用getattr来获取一个属性,该属性的名称作为字符串存储在另一个变量中:

getattr(a, b[0])(c)

Your current code is looking for an attribute named b on the a set. 您当前的代码是寻找一个名为属性ba集。

You can't do that kind of indirect attribute access using the dot operator in Python. 您无法在Python中使用点运算符进行这种间接属性访问。 Use getattr() instead: 使用getattr()代替:

>>> a = {1, 2, 3, 4, 5}
>>> c = {3, 4, 5, 6, 7}
>>> b = ['intersection_update', '10']
>>> getattr(a, b[0])(c)
>>> a
{3, 4, 5}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM