如何重写Enum类以返回成员值而不是成员对象? - python

我有一个枚举类,用于常见系统路径的快捷方式:

    _HOME = str(Path().home())

    class Shortcuts(Enum):
        RECENTS = _HOME + '/Recents'
        DESKTOP = _HOME + '/Desktop'
        DOCUMENTS = _HOME + '/Documents'
        DOWNLOADS = _HOME + '/Downloads'
        APPLICATIONS = '/Applications'
        LIBRARY = '/Library'
        SYSTEM = '/System'
        USERS = '/Users'
        TRASH = _HOME + '/.Trash'

我希望能够访问返回其值而不是成员对象的成员。

    print(Shortcuts.RECENTS)
    > '/Users/username/Recents'

我试过重写__getitem__,__getattr___和__getattribute__超类方法,但是在不经修改就实现它们时会出错。

def __getattribute__(self, item): #type error: str obj not callable
    return item

def __getattribute__(self, item): #type error: str obj not callable
    return item.value

def __getitem__(self, item): #returns same object if item.value, item.name, ..etc
    return item 

我想念什么?

参考方案

您可以通过重载__repr__方法来完成此操作,如下所示:

def __repr__(self):
   return self._value_

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python:传递记录器是个好主意吗? - python

我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…

Python:如何根据另一列元素明智地查找一列中的空单元格计数? - python

df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice','Jane', 'Alice','Bob', 'Alice'], 'income…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…