python - __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'
我错过了什么?
解决方案
__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)
推荐阅读
- java - 命名应用程序包是否有任何严格的规则
- bootstrap-4 - Angular Material TextArea 自动调整大小不适用于 bootstrap 4
- java - 是否需要在本地安装mysql才能在另一台计算机上保存和检索sql数据?
- c++ - C++中的嵌套结构
- jenkins - 如何在电子邮件中使用 Jenkins 发送最新附件?
- file - NiFi - TailFile - 多个文件
- php - laravel 5.5 电子邮件通知未更新内容
- java - 使用 DAO 模式对数据进行建模和访问
- python-2.7 - 两次启动同一个线程
- c++ - 从 tcp 迁移到 udp 时,“acceptor”不是“boost::asio::ip::udp”的成员