我有一个类属性,我想在运行时填充它,但我不想传递值。我现在要做的是:
怪异的u类.py
class WeirdClass:
prop = NotImplementedError
运行时文件.py
from weird_class import WeirdClass
PROP = 'somevalue'
class WeirdClassChild(WeirdClass):
prop = PROP
这是可行的,但是每当我创建WeirdClassChild
时,我就必须设置prop
值,这很恼人
我想要的是WeirdClassChild
自动选取PROP全局变量,而不需要我特别告诉它
我想做一些类似的事情:
class WeirdClass:
prop = __global_namespace__.PROP
这在python中是可能的吗
您可以使用元类:
从python3.6开始,似乎可以使用^{} 来完成
基于您上次对如何使用它的评论,为什么不添加另一个基类呢
可以使用
inspect
确定实例化类的上下文:我不一定推荐,但如果你有充分的理由这么做
相关问题 更多 >
编程相关推荐