如何在使用Python中使用方括号的类中实现一种方法(例如Pandas DataFrame中的LOC)



此答案清楚而简单地说明了如何在类中使用__getitem__方法来实现self[key]的评估。我想知道如何在与pandas DataFrame类中的 lociloc等括号内一起创建方法

熊猫中的索引方法似乎定义为类本身。但是,看着DataFrame班级,我尚不清楚这些如何被调用。因此,如果我有自己的班级,并且想创建一种与括号合作的方法,我将如何实现?

基于User803422建议,我已经设置了以下简单代码,该代码似乎正在工作:

class B:
    def __init__(self, a):
        self.a = a
    def __getitem__(self, value):
        return self.a[-value]
class A:
    def __init__(self, lst):
        self.lst = lst
    def __getitem__(self, value):
        return self.lst[value]
    b = B(lst)
x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
​
a = A(x)
print(a[2])
print(a.b[2])

此返回:

>>> c
>>> f

这是正确的方法吗?

用户803422答案没有错,但是pandas dataframes中的loc被用作属性(请参阅LOC文档),或多或少地类似于:

class A:
    def __init__(self, lst):
        self.lst = lst
    def __getitem__(self, value):
        return self.lst[value]
    @property
    def b(self):
        return B(self)
class B:
    def __init__(self, a):
        self.a = a
    def __getitem__(self, value):
        return self.a[-value]

ps:

正如ICVriend在评论中指出的那样,在我的示例中,每次调用B方法时都会创建一个新的索引对象B。而在用户803422代码中,索引是在开始时生成的。如果实例后更改了第一个属性,这可能会很麻烦。请参阅下面的两个示例。

>>> # edd313
>>> x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> a = A(x)
>>> a.lst = [1, 2, 3]
>>> print(a.b[2])
2
>>> # user803422
>>> x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> a = A(x)
>>> a.lst = [1, 2, 3]
>>> print(a.b[2])
f

呢?

class A:
    def __getitem__(self, key):
        print("__getitem__: %s, value=%s" % (type(key), str(key)))
a=A()
a[2]
a[2,5]
a['a':'f']
a['a':'f', 56]

输出为:

__getitem__: <type 'int'>, value=2
__getitem__: <type 'tuple'>, value=(2, 5)
__getitem__: <type 'slice'>, value=slice('a', 'f', None)
__getitem__: <type 'tuple'>, value=(slice('a', 'f', None), 56)

编辑(澄清原始问题之后):

您必须如下移动b = B(lst)行:

class A:
    def __init__(self, lst):
        self.lst = lst
        self.b = B(lst)
    def __getitem__(self, value):
        return self.lst[value]

相关内容

最新更新