2012-11-21 110 views
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' 
+2

为什么不设置默认为'0'? – ecatmur

回答

0
def __init__(self, first=1, second=2, third=3, fourth=None, fifth=None): 
    if first is None: 
     first = 0 
    else: 
     self.first = first 

则反而会加重为零,无副作用,而不是None

你也可以改变一部分,你把它们加起来并测试None第一,但这个是打字可能不太。

0
class test(object): 
    def __setitem__(self, key, value): 
     if key in ['first', 'second', 'third', 'fourth', 'fifth']: 
      self.__dict__[key]=value 
     else: 
      pass #or alternatively "raise KeyError" or your custom msg 


    def get_sum(self): 
     sum=0 
     for x in self.__dict__: 
      sum+=self.__dict__[x] 
     return sum 

nk=test() 
nk['first']=3 
nk['fifth']=5 
nk['tenth']=10 
print nk.get_sum() 

输出:

>>> 8