我正在尝试在运行时定义__call__
dunder方法,但没有成功。代码如下:
class Struct:
pass
result=Struct()
dictionary={'a':5,'b':7}
for k,v in dictionary.items():
setattr(result,k,v)
result.__call__=lambda self: 2
但是,解释器返回错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'Struct' object is not callable
但是,如果我从一开始就添加dunder方法,那么所有神奇的工作都会起作用:
class Foo():
def __call__(self):
return 42
foo=Foo()
foo() #returns 42
我在Windows 64位计算机上使用Python 3.4。
我在哪里做错了?
答案 0 :(得分:3)
<强>被修改强>
您可以通过将var ajax = function (arg) {
if (typeof arg.method !== "undefined" && typeof arg.url !== "undefined" && typeof arg.async !== "undefined"
&& typeof arg.success !== "undefined" && typeof arg.data !== "undefined") {
var xmlhttp, i = 0,
versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
for ( ; i < versions.length; i++) {
try {
xmlhttp = new ActiveXObject(versions[i]); break;
} catch (e) { }
}
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
arg.success(xmlhttp.responseText);
} else if (xmlhttp.status == 400) {
console.log("There was an error 400");
} else {
console.log("UNSUCCESSFUL");
}
}
}
xmlhttp.open(arg.method, arg.url, arg.async);
xmlhttp.send(arg.data);
console.log("Method: " + arg.method + "\nURL: " + arg.url + "\nAsync: " + arg.async + "\nData: " + arg.data + "\n");
}
};
添加到类对象来附加__call__
:
Struct.__call__ = lambda self: 2
但是如果你想为每个实例获得不同的值,你应该:
class Struct:
def __call__(self):
return self._call_ret
result=Struct()
dictionary={'a':5,'b':7}
for k,v in dictionary.items():
setattr(result,k,v)
result._call_ret = 2
print(result())
@Blckknght谢谢。