Questions tagged «default-arguments»


6
如何将实例成员的默认参数值传递给方法?
我想使用实例的属性值将默认参数传递给实例方法: class C: def __init__(self, format): self.format = format def process(self, formatting=self.format): print(formatting) 尝试这样做时,出现以下错误消息: NameError: name 'self' is not defined 我希望该方法的行为如下: C("abc").process() # prints "abc" C("abc").process("xyz") # prints "xyz" 这是什么问题,为什么这不起作用?我该如何做呢?

3
是否可以通过const引用返回默认参数的值?
是否可以通过const引用返回默认参数的值,如以下示例所示: https://coliru.stacked-crooked.com/a/ff76e060a007723b #include <string> const std::string& foo(const std::string& s = std::string("")) { return s; } int main() { const std::string& s1 = foo(); std::string s2 = foo(); const std::string& s3 = foo("s"); std::string s4 = foo("s"); }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.