相关疑难解决方法(0)

模块上的__getattr__

如何__getattr__在模块上实现类的等价?

当调用模块静态定义的属性中不存在的函数时,我希望在该模块中创建一个类的实例,并在模块上的属性查找中使用与失败相同的名称调用其上的方法.

class A(object):
    def salutation(self, accusative):
        print "hello", accusative

# note this function is intentionally on the module, and not the class above
def __getattr__(mod, name):
    return getattr(A(), name)

if __name__ == "__main__":
    # i hope here to have my __getattr__ function above invoked, since
    # salutation does not exist in the current namespace
    salutation("world")
Run Code Online (Sandbox Code Playgroud)

这使:

matt@stanley:~/Desktop$ python getattrmod.py 
Traceback (most recent call last):
  File "getattrmod.py", line 9, in <module>
    salutation("world")
NameError: name 'salutation' is not …
Run Code Online (Sandbox Code Playgroud)

python module attributeerror getattr python-3.x

114
推荐指数
7
解决办法
4万
查看次数

模块的属性可以与对象相同吗?

使用python属性,我可以这样做

obj.y 
Run Code Online (Sandbox Code Playgroud)

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

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

module.y 
Run Code Online (Sandbox Code Playgroud)

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

python properties python-module

87
推荐指数
5
解决办法
2万
查看次数