模块可以像对象一样拥有属性吗? [英] Can modules have properties the same way that objects can?

查看:45
本文介绍了模块可以像对象一样拥有属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python属性,我可以做到

With python properties, I can make it such that

obj.y 

调用一个函数而不是仅仅返回一个值.

calls a function rather than just returning a value.

有没有办法用模块来做到这一点?我有一个我想要的案例

Is there a way to do this with modules? I have a case where I want

module.y 

调用一个函数,而不是仅仅返回存储在那里的值.

to call a function, rather than just returning the value stored there.

推荐答案

只有新样式类的实例才能有属性.你可以让 Python 相信这样的实例是一个模块,方法是将它隐藏在 sys.modules[thename] = theinstance 中.因此,例如,您的 m.py 模块文件可能是:

Only instances of new-style classes can have properties. You can make Python believe such an instance is a module by stashing it in sys.modules[thename] = theinstance. So, for example, your m.py module file could be:

import sys

class _M(object):
    def __init__(self):
        self.c = 0
    def afunction(self):
        self.c += 1
        return self.c
    y = property(afunction)

sys.modules[__name__] = _M()

这篇关于模块可以像对象一样拥有属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆