首页 > 解决方案 > __getattr__ 返回列表的索引

问题描述

我正在尝试获取列表元素的索引(ID),并能够通过它们的名称作为属性来调用它。

class Page_ids(object):

    def __init__(self):
        self.values = ['PAGE1', 'PAGE2', 'PAGE3', 'PAGE4']

    def __getattr__(self, name):
        return self.values.index(name)

print(Page_ids.PAGE3)

在此示例中,打印应返回 2,但它返回:

AttributeError: type object 'Page_ids' has no attribute 'PAGE3'

我错过了什么?

标签: pythonpython-3.x

解决方案


__getattr__仅在类的实例上调用,因此您需要创建一个。

class Page_ids(object):

    def __init__(self):
        self.values = ['PAGE1', 'PAGE2', 'PAGE3', 'PAGE4']

    def __getattr__(self, name):
        return self.values.index(name)

page = Page_ids()
print(page.PAGE3)

推荐阅读