简体   繁体   English

Python class 返回字典列表作为点符号

[英]Python class return list of dictionaries as dot notation

Imagine you have a class in python that returns:假设您在 python 中有一个 class 返回:

d=[{'source_id': '1', 'source_desc': 'XML1'},
 {'source_id': '2', 'source_desc': 'XML2'},
 {'source_id': '3', 'source_desc': 'XML3'}]

Imagine the class is called:假设 class 被称为:

class ddata():
    def __init__(var):
        self.var=method_class(var)

    def method_class(self,v):
        ´´´do stuff / dummy method´´´
        return v
        

Initializing:初始化:

mydata=ddata(d)

Is it possible in python to add a particular method to the class in order to allow the following: pseudocode:是否可以在 python 中向 class 添加特定方法以允许以下操作:伪代码:

mydata.1.source_desc (would be XML1)

EDIT The intention is that one, and only one of the keys is used as enter dot notation.编辑目的是一个,并且只有一个键用作输入点符号。 in this case the numbers.在这种情况下,数字。 the numbers are int or str.数字是 int 或 str。 AND ARE NOT NECESSARILY consecutive, what invalidate solutions based on position on the returned list.并且不一定是连续的,什么使返回列表中基于 position 的解决方案无效。

It is possible to use integers as identifiers in Python, contrary to what @BoarGules said.可以在 Python 中使用整数作为标识符,这与@BoarGules 所说的相反。 Just not in source code.只是不在源代码中。 Proof:证明:

>>> class Foo: pass
>>> foo = Foo()
>>> foo.__setattr__("1", "a number!")
>>> foo.1
  File "<input>", line 1
    foo.1
        ^
SyntaxError: invalid syntax
>>> foo.__getattribute__("1")
'a number!'

So here is a solution:所以这是一个解决方案:

from typing import Dict, List

d = [
    {'source_id': '1', 'source_desc': 'XML1'},
    {'source_id': '2', 'source_desc': 'XML2'},
    {'source_id': '3', 'source_desc': 'XML3'},
    {'source_id': 'forty_two', 'source_desc': 'XML42'}
]


class DData:
    def __init__(self, d: List[Dict[str, str]]):
        for line in d:
            source_id = line["source_id"]
            source_desc = line["source_desc"]
            self.__setattr__(source_id, source_desc)

    def __getitem__(self, item):
        return self.__getattribute__(item)


my_data = DData(d)
print(my_data["1"])  # XML1
print(my_data.forty_two)  # XML42
# print(my_data.1)  # SyntaxError: invalid syntax

I used __getitem__ because I find it more friendly than __getattribute__ .我使用__getitem__因为我发现它比__getattribute__更友好。

But using just a properly-defined dict would do the same, and be much simpler:但是只使用一个正确定义的 dict 会做同样的事情,而且要简单得多:

my_dict = {line["source_id"]: line["source_desc"] for line in d}
print(my_dict["1"])  # XML1
print(my_dict["forty_two"])  # XML42

I would recommend not using identifiers that you cannot write in source code ( 1 ).我建议不要使用您无法在源代码中编写的标识符 ( 1 )。 And I think using the "dict notation" ( x["y"] ) is not very different from the dot notation ( xy ) but in your case much more simpler to maintain.而且我认为使用“字典表示法”( x["y"] )与点表示法( xy )没有太大区别,但在您的情况下更易于维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM