如果Python没有三元条件运算符,是否可以使用其他语言结构模拟一个?
我想使用实例的属性值将默认参数传递给实例方法:
class C:
def __init__(self, format):
self.format = format
def process(self, formatting=self.format):
print(formatting)
Run Code Online (Sandbox Code Playgroud)
尝试时,我收到以下错误消息:
NameError: name 'self' is not defined
Run Code Online (Sandbox Code Playgroud)
我希望该方法的行为如下:
C("abc").process() # prints "abc"
C("abc").process("xyz") # prints "xyz"
Run Code Online (Sandbox Code Playgroud)
这里有什么问题,为什么这不起作用?我怎么能做这个工作?