1

いくつかのデフォルト引数がNoneに設定されているクラスがある場合、それらがNoneである場合はそれらを無視し、そうでない場合(または少なくとも1つがNoneでない場合)にそれらを使用するにはどうすればよいですか?

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'
4

2 に答える 2

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
于 2012-11-21T14:38:12.543 に答える
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が、これはおそらくタイピングが少なくなります。

于 2012-11-21T12:13:35.680 に答える