简体   繁体   English

方括号在Python中应用于“self”

[英]Square brackets applied to “self” in Python

I've come across some code where square brackets are used on "self". 我遇到过一些代码,其中方括号用于“自我”。 I'm not familiar with this notation and as I'm trying to get my head around source code not written by me, it makes it difficult to understand what sort of object is being dealt with here. 我不熟悉这种符号,因为我试图理解我不是由我编写的源代码,所以很难理解这里处理的是什么类型的对象。

The example I've come across is in the Natural Language Toolkit for Python here . 我遇到的例子是在自然语言工具包为Python 这里 You can find an example of what I mean if you ctrl-F self[context] . 如果ctrl-F self[context]你可以找到我的意思的例子。

It may not be possible to tell exactly how it's being used without more context, but here's a snippet with an example: 如果没有更多的上下文,可能无法确切地说明它是如何被使用的,但这里有一个示例片段:

context = tuple(context)
if (context + (word,) in self._ngrams) or (self._n == 1):
     return self[context].prob(word)
else:
     return self._alpha(context) * self._backoff.prob(word, context[1:])

square brackets are python's way of saying "call the __getitem__ (or __setitem__ ) method." 方括号是python说“调用__getitem__ (或__setitem__ )方法”的方式。

x = a[...]  #call a.__getitem__(...)
a[...] = x  #call a.__setitem__(...)
del a[...]  #call a.__delitem__(...)

In your case, there's nothing different between self and a . 在你的情况下, selfa之间没有什么不同。 In fact, there's nothing special about self in a class's method at all. 事实上,在课程方法中, self并没有什么特别之处。 The first argument passed to a method is an instance of the class, but you can call that argument anything you want. 传递给方法的第一个参数是类的实例,但您可以根据需要调用该参数。 self is just a (very highly recommended) convention. self只是一个(非常强烈推荐)的惯例。

self is just an identifier, so this is the same as doing [] on any other object. self只是一个标识符,所以这与在任何其他对象上执行[]相同。 For this to work, self has to implement __getitem__ , the "magic method" that is invoked by the square brackets. 为了实现这一点, self必须实现__getitem__ ,即方括号调用的“魔术方法”。

Eg 例如

class OneItemContainer(object):
    def __init__(self, value):
        self.value = value

    def __getitem__(self, i):
        if i != 0:
            raise IndexError("this container can only hold one object")
        return self.value

Now you can do 现在你可以做到

container = OneItemContainer("ham")
print(container[0])  # will print ham

But there's no reason why you shouldn't be able use [] from within a method: 但是你没有理由不能在方法中使用[]

    # on the previous class
    def __repr__(self):
        return "OneItemContainer(%r)" % self[0]

this 这个

def __getitem__(self, item):
    return self._model[tuple(item)]

allows iterating the data owned by the object. 允许迭代对象拥有的数据。

object.__getitem__(self, key)
Called to implement evaluation of self[key]. 被称为实施自我评估[关键]。 For sequence types, the accepted keys should be integers and slice objects. 对于序列类型,接受的键应该是整数和切片对象。 Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. 请注意,负索引的特殊解释(如果类希望模拟序列类型)取决于__getitem__()方法。 If key is of an inappropriate type, TypeError may be raised; 如果key是不合适的类型,则可能引发TypeError; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. 如果序列的索引集之外的值(在对负值进行任何特殊解释之后),则应引发IndexError。 For mapping types, if key is missing (not in the container), KeyError should be raised. 对于映射类型,如果缺少键(不在容器中),则应引发KeyError。

http://www.python.org/dev/peps/pep-0234/ http://www.python.org/dev/peps/pep-0234/

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

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