如何__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中),一旦初始化__init__
,不接受新属性,但接受现有属性的修改.我可以看到有几种黑客方法可以做到这一点,例如有一个__setattr__
方法,比如
def __setattr__(self, attribute, value):
if not attribute in self.__dict__:
print "Cannot set %s" % attribute
else:
self.__dict__[attribute] = value
Run Code Online (Sandbox Code Playgroud)
然后__dict__
直接在里面编辑__init__
,但我想知道是否有"正确"的方法来做到这一点?