1
如果我們有一個默認參數設置爲None的類,如果它們是None,我們如何忽略它們,如果它們不是(或者它們中的至少一個不是None),那麼使用它們?如何忽略Python類屬性?
class Foo:
def __init__(self, first=1, second=2, third=3, fourth=None, fifth=None):
self.first = first
self.second = second
self.third = third
self.fourth = fourth
self.fifth = fifth
self.sum = self.first + self.second + self.third + self.fourth + self.fifth
return self.sum
>>> c = Foo()
Traceback (most recent call last):
File "<pyshell#120>", line 1, in <module>
c = Foo()
File "<pyshell#119>", line 8, in __init__
self.sum = self.first + self.second + self.third + self.fourth + self.fifth
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
爲什麼不設置默認爲'0'? – ecatmur