如果 Python 对象是“可订阅的”,这意味着什么? 或不?

发布于 2024-07-06 18:37:25 字数 24 浏览 5 评论 0原文

哪些类型的对象属于“可订阅”范围?

Which types of objects fall into the domain of "subscriptable"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

和影子一齐双人舞 2024-07-13 18:37:25

它基本上意味着该对象实现了 __getitem__() 方法。 换句话说,它描述的是“容器”对象,意味着它们包含其他对象。 这包括字符串、列表、元组和字典。

It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

沩ん囻菔务 2024-07-13 18:37:25

在我的脑海中,以下是唯一可订阅的内置函数:

string:  "foobar"[3] == "b"
tuple:   (1,2,3,4)[3] == 4
list:    [1,2,3,4][3] == 4
dict:    {"a":1, "b":2, "c":3}["c"] == 3

但是 mpadi 的答案 是正确的 - 任何实现 __getitem__ 的类是可下标的

Off the top of my head, the following are the only built-ins that are subscriptable:

string:  "foobar"[3] == "b"
tuple:   (1,2,3,4)[3] == 4
list:    [1,2,3,4][3] == 4
dict:    {"a":1, "b":2, "c":3}["c"] == 3

But mipadi's answer is correct - any class that implements __getitem__ is subscriptable

傲世九天 2024-07-13 18:37:25

下标在计算中的含义是:
“在程序中单独或与其他符号一起使用的符号(理论上写为下标,但实际上通常不是),用于指定数组的元素之一。”

现在,在 @user2194711 给出的简单示例中,我们可以看到附加元素无法成为列出原因有两个:-

  1. 我们并没有真正调用方法append; 因为它需要 () 来调用它。

  2. 错误表明该函数或方法不可下标; 意味着它们不能像列表或序列那样可索引。

现在看一下:-

>>> var = "myString"
>>> def foo(): return 0
... 
>>> var[3]
't'
>>> foo[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable

这意味着 function 中没有下标或元素,就像它们出现在序列中一样; 我们无法像通常那样在 [] 的帮助下访问它们。

还; 正如 mpadi 在他的回答中所说; 它基本上意味着该对象实现了 __getitem__() 方法。 (如果它是可订阅的)。
因此产生了错误:

arr.append["HI"]

类型错误:“builtin_function_or_method”对象不可下标

The meaning of subscript in computing is:
"a symbol (notionally written as a subscript but in practice usually not) used in a program, alone or with others, to specify one of the elements of an array."

Now, in the simple example given by @user2194711 we can see that the appending element is not able to be a part of the list because of two reasons:-

  1. We are not really calling the method append; because it needs () to call it.

  2. The error is indicating that the function or method is not subscriptable; means they are not indexable like a list or sequence.

Now see this:-

>>> var = "myString"
>>> def foo(): return 0
... 
>>> var[3]
't'
>>> foo[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable

That means there are no subscripts or say elements in function like they occur in sequences; and we cannot access them like we typically do, with the help of [].

Also; as mipadi said in his answer; It basically means that the object implements the __getitem__() method. (if it is subscriptable).
Thus the error produced:

arr.append["HI"]

TypeError: 'builtin_function_or_method' object is not subscriptable

孤寂小茶 2024-07-13 18:37:25

如果“可编写脚本”

可编写脚本的对象是记录对其执行的操作的对象,并且可以将它们存储为可以重播的“脚本”。

例如,请参阅: 应用程序脚本框架

如果“可订阅”

现在,如果 Alistair 不知道他问什么并且真正意味着“可订阅”对象(由其他人编辑),那么(正如 mipadi 也回答的那样)这是正确的:

可订阅对象是实现 __getitem__< 的任何对象/code> 特殊方法(想想列表、字典)。

if “scriptable”

A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.

For example, see: Application Scripting Framework

if “subscriptable”

Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:

A subscriptable object is any object that implements the __getitem__ special method (think lists, dictionaries).

孤城病女 2024-07-13 18:37:25

我也有同样的问题。 我正在

arr = []
arr.append["HI"]

这样做,所以使用 [ 导致了错误。 应该是 arr.append("HI")

I had this same issue. I was doing

arr = []
arr.append["HI"]

So using [ was causing error. It should be arr.append("HI")

把人绕傻吧 2024-07-13 18:37:25

作为此处早期答案的推论,这通常表明您认为您有一个列表(或字典或其他可下标的对象),但实际上您没有。

例如,假设您有一个函数应该返回一个列表;

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']

现在,当您调用该函数,并且 something_happens() 由于某种原因没有返回 True 值时,会发生什么? if 失败了,所以你失败了; gimme_things 不会显式返回任何内容——所以事实上,它会隐式返回 None。 那么这段代码:

things = gimme_things()
print("My first thing is {0}".format(things[0]))

将会失败,并显示“NoneType object is not subscriptable”,因为,things is None,所以你正在尝试做 < code>None[0] 这没有意义,因为......错误消息所说的内容。

有两种方法可以修复代码中的此错误 - 第一种是通过在尝试使用 things 之前检查它实际上是否有效来避免错误;

things = gimme_things()
if things:
    print("My first thing is {0}".format(things[0]))
else:
    print("No things")  # or raise an error, or do nothing, or ...

或者等效地捕获 TypeError 异常;

things = gimme_things()
try:
    print("My first thing is {0}".format(things[0]))
except TypeError:
    print("No things")  # or raise an error, or do nothing, or ...

另一个方法是重新设计gimme_things,以确保它始终返回一个列表。 在这种情况下,这可能是更简单的设计,因为这意味着如果有很多地方有类似的错误,它们可以保持简单和惯用。

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']
    else:  # make sure we always return a list, no matter what!
        logging.info("Something didn't happen; return empty list")
        return []

当然,您在 else: 分支中放置的内容取决于您的用例。 也许您应该在 something_happens() 失败时引发异常,以使实际出错的地方更加明显和明确? 在您自己的代码中添加异常是让您自己在出现故障时准确了解情况的重要方法!

(另请注意,后一个修复仍然没有完全修复该错误 - 它阻止您尝试下标 Nonethings[0] 仍然是 things 是一个空列表时,出现 IndexError 如果你有一个 try,你可以执行 except (TypeError, IndexError) 来捕获它。 , 也。)

As a corollary to the earlier answers here, very often this is a sign that you think you have a list (or dict, or other subscriptable object) when you do not.

For example, let's say you have a function which should return a list;

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']

Now when you call that function, and something_happens() for some reason does not return a True value, what happens? The if fails, and so you fall through; gimme_things doesn't explicitly return anything -- so then in fact, it will implicitly return None. Then this code:

things = gimme_things()
print("My first thing is {0}".format(things[0]))

will fail with "NoneType object is not subscriptable" because, well, things is None and so you are trying to do None[0] which doesn't make sense because ... what the error message says.

There are two ways to fix this bug in your code -- the first is to avoid the error by checking that things is in fact valid before attempting to use it;

things = gimme_things()
if things:
    print("My first thing is {0}".format(things[0]))
else:
    print("No things")  # or raise an error, or do nothing, or ...

or equivalently trap the TypeError exception;

things = gimme_things()
try:
    print("My first thing is {0}".format(things[0]))
except TypeError:
    print("No things")  # or raise an error, or do nothing, or ...

Another is to redesign gimme_things so that you make sure it always returns a list. In this case, that's probably the simpler design because it means if there are many places where you have a similar bug, they can be kept simple and idiomatic.

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']
    else:  # make sure we always return a list, no matter what!
        logging.info("Something didn't happen; return empty list")
        return []

Of course, what you put in the else: branch depends on your use case. Perhaps you should raise an exception when something_happens() fails, to make it more obvious and explicit where something actually went wrong? Adding exceptions to your own code is an important way to let yourself know exactly what's up when something fails!

(Notice also how this latter fix still doesn't completely fix the bug -- it prevents you from attempting to subscript None but things[0] is still an IndexError when things is an empty list. If you have a try you can do except (TypeError, IndexError) to trap it, too.)

所谓喜欢 2024-07-13 18:37:25

这个问题是nr。 搜索结果有 1 个,并且浏览次数最多,所以我会在这里发布。

我的案例

(404, b'{"url":"https://example.com"}')

尝试获取第一个值,访问obj[0]返回对象不可下标

正如建议的另一个答案,尝试循环遍历它但得到对象不可迭代。

解决方案

obj.args[0]

故障排除

调用 print(dir(obj)) 并查看是否存在可以让您访问该值的方法或属性。

This question is the nr. 1 result on search and it has the most views, so I'll post here.

My case

(404, b'{"url":"https://example.com"}')

Tried to get the first value, accessing obj[0] returned object is not subscriptable.

As another answer suggested, tried looping through it but got object is not iterable.

Solution

obj.args[0]

Troubleshooting

Call print(dir(obj)) and see if there's a method or attribute that might give you access to the value.

本宫微胖 2024-07-13 18:37:25

基本上,如果您在上述对象的类型转换之后修改或添加任何字段而不是之前执行此操作,则会出现此错误。

Basically this error will appear in case you are modifying or adding any field after type casting for the mentioned object instead of doing it before.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文