有没有我可以使用ANIMAL_CHOICES.RABBIT在Python中获取值?

2024-05-14 08:44:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用以下数据:

我假设:

ANIMAL_CHOICES = {
    "RABBIT":"RABBIT",
    "CAMEL":"CAMEL",
}

print(ANIMAL_CHOICES["RABBIT"]) # there I can get the "RABBIT", and can see the RABBIT easily.

你看,我可以把ANIMAL_CHOICES放在一个文件中,当我使用它时,我可以用ANIMAL_CHOICES["RABBIT"]来做。我可以很容易地通过它在其他文件中的键来知道这个值,但是有一个缺陷,我将转到源代码查看这个键

那么,是否有更整洁的方法来达到这种效果呢

我的意思是我是否可以用ANIMAL_CHOICES.RABBIT得到"RABBIT"


编辑

我的意思是,有没有其他python数据类型可以用来获得效果?你看这本词典达不到要求


Tags: and文件the数据getcanchoicesthere
3条回答
class My_dict(dict):
    def __getattribute__(self, name):
        return self[name]


d = My_dict({
    "RABBIT": "RABBIT",
    "CAMEL": "CAMEL",
})

print(d.RABBIT)

您可以定义自己的类,该类根据数据结构的键生成属性

class animal_properties:
 def __init__(self, dictionary):
        for k, v in dictionary.items():
            setattr(self, k, v)
animal = animal_properties({"RABBIT":"RABBIT", "CAMEL":"CAMEL"})
animal.RABBIT

仅使用类作为命名空间:

class AnimalChoices(object):
    RABBIT = "RABBIT"
    CAMEL = "CAMEL"

print(AnimalChoices.RABBIT)

相关问题 更多 >

    热门问题