len() vs __len__: TypeError: 'float' object cannot be interpreted as an integer

len() vs __len__: TypeError: 'float' object cannot be interpreted as an integer

我遇到了一个奇怪的错误,我认为这不是我的代码的问题。

这是我得到的物品:

这是我想要做的,

  1. 我在边界定义了__len__,这样len(Boundary([1, 10])) #=> 9
class Boundary:
    def __len__(self):
            return abs(self.high - self.low)
  1. 在 Lim 对象中,我有 self.boundaries,它是 Boundary 对象的列表。在定义了边界 __len__ 的情况下,我将 Lim 的 __len__ 编码如下:
class Lim:
    def __len__(self):
            return sum([len(bd) for bd in self.boundaries])

问题是这样发生的,组成如下:

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

但是这样的构图:

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

然而,代码最终以这种组合执行:

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

为什么将 len() 更改为 __len__() 会消除错误?如果你能提供一些帮助,我会很高兴。

正如评论中指出的那样,len 与您的用例不兼容。我不知道您的解决方案需要多灵活,但我提出了一个最低限度的工作示例:

from typing import List

def dist(boundary: object, m='euclidean') -> float:
    """Computes a given distance for object-typed boundaries.
    """
    return boundary.__dist__(m)

def converge(lim: object) -> float:
    """_Integrates_ the distances over boundaries."""
    return lim.__converge__()


class Boundary(object):
    low = 0
    high = 0
    
    def __init__(self, lo: float, hi: float):
        self.low = lo
        self.high = hi
        
    def __dist__(self, m: str) -> float:
        if m == 'euclidean':
            return abs(self.high - self.low)
        else:
            raise Error(f'Unknown distance {m}')

class Lim(object):
    boundaries = []
    def __init__(self, boundaries: List[Boundary]):
        self.boundaries = boundaries

    def __converge__(self) -> float:
        return sum([dist(bd) for bd in self.boundaries])

print(converge(Lim([Boundary(1.0, 10.0), Boundary(20.0, 30.0)])))
# expect abs(10-1) + abs(30-20) = 9+10 = 19

这就是你想要的(据我所知)。此外,您可以引入基于 Boundary class 的不同 Boundary classes。对于基数 Boundary class,您可以引入不同的距离度量,对于 Lim class(作为基数 class),您可以创建不同的收敛方案。虽然这个答案并没有就您最初的问题提出任何一点(都在评论中),但它是否以某种方式为您勾勒出前进的道路?