gpt4 book ai didi

python元编程

转载 作者:太空狗 更新时间:2023-10-30 02:23:42 25 4
gpt4 key购买 nike

我正在尝试归档一个任务,结果发现它有点复杂,因为我不太擅长 Python 元编程。

我想要一个带有函数get_location(name) 的模块locations,它返回一个定义在文件夹位置/文件中的类,并将名称传递给函数.类的名称类似于 NameLocation。

所以,我的文件夹结构:

program.py
locations/
__init__.py
first.py
second.py

program.py 将与:

from locations import get_location
location = get_location('first')

location 是在 first.py smth 中定义的类,如下所示:

from locations import Location # base class for all locations, defined in __init__ (?)
class FirstLocation(Location):
pass

等等

好吧,我已经尝试了很多importgetattribute 语句,但现在我感到无聊并投降。如何存档此类行为?


我不知道为什么,但是这段代码

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'>

位置模块!为什么?!

最佳答案

您确实需要__import__ 模块;之后,从中获得 attr 并不难。

import sys

def get_location(name):
fullpath = 'locations.' + name
package = __import__(fullpath)
module = sys.modules[fullpath]
return getattr(module, name.title() + 'Location')

编辑:__import__返回包,所以你还需要一个getattr,见the docs (并仔细阅读所有部分——“照我说的做,不要照我做的去做”;-)。

关于python元编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2482060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com