我发现了一段 Python 代码,它的技术实现看起来像这样:
def bar(b):
return b*2
class MyClass(object):
def __init__(self, a):
self.a = a
self.b = 10
def foo(self, b=None):
return bar(b if b is not None else self.b)
所以这个类有一个固定的属性
b
,它作为 classmethod foo
的默认输入参数,如果没有传入参数。请假设在这种情况下,b
应该是一个浮点数。请忽略未使用的
self.a
,它被用于其他地方 - 我只是想确保您看到构造函数设置了属性。使用方法如下:
c = MyClass(2)
c.foo(3) # returns 3*2 = 6
c.foo() # returns 10*2 = 20
在这种情况下,我想知道
foo
方法是否是将b
的默认值设置为self.b
的好方法?以下两个建议中的哪一个更理想?如果有的话:为什么?
def foo(self, b=None):
return bar(b or self.b)
或者
def foo(self, b=self.b):
return bar(b)
self.b if b is None else b
。 - PM 2Ringself.b if b is None else b
时,我假设传递参数b
将会覆盖默认行为,即使用self.b
。而阅读b if b is not None else self.b
时,我假设参数b
被使用,但如果缺少该参数,则会使用默认值self.b
。结果是相同的,但语义不同。 - DainDwarf