在通过编码审查某些代码时,Codacy为以下代码提出了一个问题:
module['exports'] = function testbot(hook) {
var request = require('request');
// The parameters passed in via the slash command POST request.
var params = hook.params;
data = {
"response_type": "ephemeral",
"text": "Immediate Response"
}
hook.res.setHeader('Content-Type', 'application/json');
console.log("returning immediate response")
hook.res.write(JSON.stringify(data), 'utf8', delay(params));
//calling end() here sends the immediate response but the POST never happens.
// but if end() is called below instead slack gives a timeout error but the POST succeeds.
//hook.res.end()
//test with 3.5 second delay
function delay(params) {
setTimeout(function () {post_response(params)},3500);
}
function post_response(params) {
console.log("posting delayed response")
// Set up the options for the HTTP request.
var options = {
// Use the Webhook URL from the Slack Incoming Webhooks integration.
uri: params.response_url,
method: 'POST',
// Slack expects a JSON payload with a "text" property.
json: {"response_type":"in_channel", "text":"Delayed response","parse":"full"}
};
// Make the POST request to the Slack incoming webhook.
request(options, function (error, response, body) {
// Pass error back to client if request endpoint can't be reached.
if (error) {
console.log(error);
hook.res.end(error.message);
} else {
console.log("post OK");
}
// calling end() here sends the POST but the immediate response is lost to a slack timeout error.
hook.res.end()
})
};
}
通过以下说明:
为什么这是一个问题?
例如,使用基类作为第一个参数调用super()是 错误:
def MyClass(OldClass): def __init__(self, arg1, arg2, *args, **kwargs) self.arg1 = arg1 self.arg2 = arg2 super(OldClass, self).__init__(*args, **kwargs)
应该是:
class AnotherOldStyleClass(OldStyleClass): def __init__(self): super(OldStyleClass, self).__init__() The super invocation
似乎要我这样做:
super(AnotherOldStyleClass, self).__init__()
或许这个:
def MyClass(OldClass):
def __init__(self, arg1, arg2, *args, **kwargs)
self.arg1 = arg1
self.arg2 = arg2
super(OldClass, self).__init__(*args, **kwargs)
有人能告诉我哪些是正确的以及为什么这是首选行为?
作为参考,docs就是我使用选项2找到的例子。
编辑:这是我的代码,因为它看起来完全正确。这解释了我的错误:
def MyClass(OldClass):
def __init__(self, arg1, arg2, *args, **kwargs)
super(MyClass, self).__init__(*args, **kwargs)
self.arg1 = arg1
self.arg2 = arg2
为什么推荐这个?
答案 0 :(得分:0)
我希望下一个例子能解释差异
class Grandparent(object):
def hello(self):
print "hi, I am Grandparent"
class Parent(Grandparent):
def hello(self):
print "hi, I am Parent"
class Child(Parent):
def test(self):
super(Parent, self).hello() # print "hi, I am Grandparent"
super(Child, self).hello() # print "hi, I am Parent"
def proper_way_to_do_same(self):
Grandparent.hello(self) # print "hi, I am Grandparent"
Parent.hello(self) # print "hi, I am Parent"