简体   繁体   English

Python:__getattr__用于模块对象

[英]Python: __getattr__ for a module object

Supposing, I have a python module called mymodule , it has the following structure: 假设我有一个名为mymodule的python模块,它具有以下结构:

""" mymodule.py """

mydata = {
    "x": 12,
    "y": 58
}

I want to access to data in the following way: 我想通过以下方式访问数据:

""" main.py """
import mymodule

print(mymodule.x) # 12
print(mymodule.y) # 58

What should I add to mymodule.py ? 我应该在mymodule.py添加什么?

I would like to know solutions for Python 2.7 and Python 3 . 我想知道Python 2.7Python 3解决方案。

As per https://stackoverflow.com/a/7668273/783836 , it seems to can be done by replacing the module with a class that does what you want: 根据https://stackoverflow.com/a/7668273/783836 ,似乎可以通过将模块替换为满足您所需的类来完成:

# module foo.py

import sys

class Foo:
    def funct1(self, <args>): <code>
    def funct2(self, <args>): <code>

sys.modules[__name__] = Foo()

Check the entire post for full details 检查整个帖子以获取详细信息

Option 1 选项1

If the only data is x and y and you don't want it dynamic you can do something like: 如果唯一的数据是xy并且您不希望它是动态的,则可以执行以下操作:

""" mymodule.py """

mydata = {
    "x": 12,
    "y": 58
}

x = mydata['x']
y = mydata['y']

Option 2 选项2

Another option is to use addict.Dict but this will require a bit of change in the import. 另一种选择是使用addict.Dict但这将需要对导入进行一些更改。

""" mymodule.py """
from addict import Dict

mydata = Dict({
    "x": 12,
    "y": 58
})

And then to use it: 然后使用它:

""" main.py""
from mymodule import mydata

print(mydata.x)
print(mydata.y)

It would be more easier to know why you need it... 知道为什么需要它会更容易...

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

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