gpt4 book ai didi

Python 模块作为类的全局实例

转载 作者:行者123 更新时间:2023-11-28 19:26:02 26 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
getattr on a module

我有一个模块,其中定义了一个 Manager 类。我希望模块创建此类的实例并将模块用作此类的“全局实例”。例如:

class Manager:

def func(self):
print('stuff')

instance = Manager()

def func():
instance.func()

有没有办法让 module.x 返回 module.instance.x? (有点像模块级属性)

更新:this question 中的答案只涵盖了我的一半用例(即,它不是重复的,那个问题问的是不同的);我还需要模块的属性也可用。示例:

class Manager:

def __init__(self):
self.x = 3

def func(self):
print('stuff')

sys.modules[__name__] = Manager()

>>> module.func
<func>
>>> module.x
3
>>> module.Manager
AttributeError

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