I met a weird bug and I don't think it's my code's problem.
Here are the objects I have got:
- Boundary: represents domain and range, such that
[1, 10]
, it has alow
attribute and ahigh
attribute, in this caselow = 1
andhigh=10
- Lim: represents union set, such that
[1, 10]U[20, 30]
, stored asself.boundaries = [Boundary([1, 10]), Boundary([20, 30])]
Here's what I am trying to do,
- I defined
__len__
in boundary, such thatlen(Boundary([1, 10])) #=> 9
class Boundary:
def __len__(self):
return abs(self.high - self.low)
- in Lim object, I have
self.boundaries
, which is a list of Boundary objects. with__len__
in Boundary defined, I coded Lim's__len__
in following:
class Lim:
def __len__(self):
return sum([len(bd) for bd in self.boundaries])
Here's how the issue occurred, with following composition:
class Boundary:
def __len__(self):
return abs(self.high - self.low)
class Lim:
def __len__(self):
return sum([len(bd) for bd in self.boundaries])
print(len(Lim([1, 10], [20, 30])))
# Traceback (most recent call last):
# File "boundary.py" in <module>
# print(len(Lim([1, 10], [20, 30])))
# File "boundary.py", in __len__
# return sum([len(bd) for bd in self.boundaries])
# File "boundary.py", in <listcomp>
# return sum([len(bd) for bd in self.boundaries])
# TypeError: 'float' object cannot be interpreted as an integer
But with this composition:
class Boundary:
def __len__(self):
return abs(self.high - self.low)
class Lim:
def __len__(self):
return sum([bd.__len__() for bd in self.boundaries])
print(len(Lim([1, 10], [20, 30])))
# Traceback (most recent call last):
# File "boundary.py",in <module>
# print(len(Lim([1, 10], [20, 30])))
# TypeError: 'float' object cannot be interpreted as an integer
However, the code finally executes with this composition:
class Boundary:
def __len__(self):
return abs(self.high - self.low)
class Lim:
def __len__(self):
return sum([bd.__len__() for bd in self.boundaries])
print(Lim([1, 10], [20, 30]).__len__())
# 19
Why changing len()
to __len__()
will dismiss the error? I will be so glad if you offer some help.