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

2024-04-25 01:20:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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
    

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

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

知道怎么回事吗

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


Tags: 对象fromself类型fields列表defresult