python 元编程
我正在尝试归档一项任务,结果发现该任务有点复杂,因为我不太擅长 Python 元编程。
我想要一个带有函数 get_location(name)
的模块 locations
,它返回在文件中的文件夹locations/中定义的类,并将名称传递给函数。类的名称类似于 NameLocation。
所以,我的文件夹结构:
program.py
locations/
__init__.py
first.py
second.py
program.py将是smth with:
from locations import get_location
location = get_location('first')
并且位置是在first.py smth中定义的类,如下所示:
from locations import Location # base class for all locations, defined in __init__ (?)
class FirstLocation(Location):
pass
等等。
好吧,我已经尝试了很多导入和getattribute 语句,但现在我感到无聊并投降。如何归档此类行为?
我不知道为什么,但是这段代码
def get_location(name):
module = __import__(__name__ + '.' + name)
#return getattr(module, titlecase(name) + 'Location')
return module
返回了
>>> locations.get_location( 'first')
<module 'locations' from 'locations/__init__.py'>
位置模块!为什么?!
I'm trying to archive a task which turns out to be a bit complicated since I'm not very good at Python metaprogramming.
I want to have a module locations
with function get_location(name)
, which returns a class defined in a folder locations/ in the file with the name passed to function. Name of a class is something like NameLocation.
So, my folder structure:
program.py
locations/
__init__.py
first.py
second.py
program.py will be smth with with:
from locations import get_location
location = get_location('first')
and the location is a class defined in first.py smth like this:
from locations import Location # base class for all locations, defined in __init__ (?)
class FirstLocation(Location):
pass
etc.
Okay, I've tried a lot of import and getattribute statements but now I'm bored and surrender. How to archive such behaviour?
I don't know why, but this code
def get_location(name):
module = __import__(__name__ + '.' + name)
#return getattr(module, titlecase(name) + 'Location')
return module
returns
>>> locations.get_location( 'first')
<module 'locations' from 'locations/__init__.py'>
the locations module! why?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您确实需要 __import__ 该模块;之后,从中获取 attr 并不难。
编辑:
__import__
返回包,所以还需要一个getattr
,参见文档(并仔细阅读所有部分 - “按我说的做,而不是照我做的做”;-)。You do need to
__import__
the module; after that, getting an attr from it is not hard.Edit:
__import__
returns the package, so you need one moregetattr
, see the docs (and read all the section carefully -- "do as I say not as I do";-).我想您正在寻找:
I think you're looking for: