Python - 无法工作超载

时间:2015-07-22 19:39:27

标签: python overloading

所有,我已经在这里工作了几天,仍然无法让这种超载工作。

Error:
    setA: {-10,-8,3,5,10,17,20}
    intSet.len(setA):
    TypeError: __len__() takes exactly 2 arguments (1 given)

代码:

class intSet(object):
    """An intSet is a set of integers
    The value is represented by a list of ints, self.vals.
    Each int in the set occurs in self.vals exactly once."""

    def __init__(self):
        """Create an empty set of integers"""
        self.vals = []

    def insert(self, e):
        """Assumes e is an integer and inserts e into self""" 
        if not e in self.vals:
            self.vals.append(e)

    >>>>>> more methods left out for brevity <<<<<<<<<<

    def __len__(self, s):
        """ Returns the length of the string provided"""
        return len(s)

非常感谢任何帮助......

2 个答案:

答案 0 :(得分:2)

__len__魔术方法不需要额外的参数。你的代码应该是

class IntSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once."""

def __init__(self):
    """Create an empty set of integers"""
    self.vals = []

>>>>>> more methods left out for brevity <<<<<<<<<<

def __len__(self):
    """Returns the number of elements in this set"""
    return len(self.vals)

然后在你的代码中以这种方式使用它

myset = IntSet()
print 'My set contains ', len(myset)
myset.insert(9)
myset.insert(10)
print 'My set contains ', len(myset)
myset.insert(9)
print 'My set contains ', len(myset)

答案 1 :(得分:0)

class intSet(object):
    def __init__(self):
        self.vals = []

    def insert(self, e):
        if not e in self.vals:
            self.vals.append(e)

    def __len__(self):
        return len(self.vals)

s = intSet()

s.insert(1)
s.insert(2)
s.insert(3)
s.insert(2)

print(len(s))
# 3