gpt4 book ai didi

python - 从不同的导入创建相同类的两个对象使它们看起来像不同的类

转载 作者:太空宇宙 更新时间:2023-11-04 05:09:38 25 4
gpt4 key购买 nike

我在 Python 中有以下文件:

  • SB/__init__.py

    from .interval import *
  • SB/interval.py

    class Interval:
    blablabla # Do stuff with intervals
    def __eq__(self, other):
    # Do comparison
    def __lt__(self, other):
    # Do comparison
    def __le__(self, other):
    # Do comparison
    def __gt__(self, other):
    # Do comparison
    def __ge__(self, other):
    # Do comparison

    def interval_from_file(filename):
    blablabla # Read the file, etc
    result = []
    for l in lines:
    fields = l.split('\t')
    ... # Validate the fields
    result.append(Interval(fields))
    return result

如果我这样做 import SB从 IPython shell 或 Jupyter 加载一些数据 SB.interval_from_file ,我得到一个 Interval 对象的列表。但是,如果我随后使用 SB.Interval 手动创建一个 Interval 对象,我无法将该对象与列表中的任何其他对象进行比较。我得到了

TypeError: '<' not supported between instances of 'Interval' and 'Interval'

知道发生了什么吗?

编辑:如果我打印对象的类型,则列表中的对象(因此来自 SB.interval_from_file 的类型为 SB.interval.Interval 而在 IPython shell 中创建的对象为 SB.Intervalinterval.Interval 类型。这种行为是预期的吗?

最佳答案

也许您的 pythonpath 包括 SB 及其父目录。

确保只包含适当的目录。

关于python - 从不同的导入创建相同类的两个对象使它们看起来像不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43327846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com