关于python类

2024-04-24 11:39:19 发布

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

我无法理解两个类如何与python交互。这是我的密码。在

class Interval(object):
     def __init__(self, s=0, e=0):
         self.start = s
         self.end = e

class Solution(object):
    def canAttendMeetings(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: bool
        """
        intervals.sort()

        for i in range(1, len(intervals)):
            if intervals[i].start < intervals[i-1].end:
                return False

        return True       

B= Solution()
print B.canAttendMeetings([[20,30],[25,30]])  

结果是“list”对象没有“start”属性 你能告诉我如何使用这两个类吗。在


Tags: self密码returnobjectinitdeftypestart
1条回答
网友
1楼 · 发布于 2024-04-24 11:39:19

您的代码会执行以下操作:

B.canAttendMeetings([[20,30],[25,30]])

那就过去了

^{pr2}$

在“间隔”参数中:

def canAttendMeetings(self, intervals):

您和我都知道它们应该是Interval,但您并没有告诉Python,据Python所知,它们是列表。第一个是一个包含[25,30]的列表。在

尝试以下操作:

class Interval(object):
     def __init__(self, s=0, e=0):
         self.start = s
         self.end = e

class Solution(object):
    def canAttendMeetings(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: bool
        """
        print type(intervals)

        return True       

B = Solution()
print B.canAttendMeetings([Interval(20,30),Interval(25,30)])  

参见:http://ideone.com/V38Erj

打印:<type 'list'>

再说一遍:interval在这一点上只是一个列表,仅仅因为它被称为intervals并不意味着它包含了什么。在

为了使列表元素成为Intervals,您必须创建一些Intervals

B.canAttendMeetings([Interval(20,30), Interval(25,30)])

完整代码:

class Interval(object):
     def __init__(self, s=0, e=0):
         self.start = s
         self.end = e

class Solution(object):
    def canAttendMeetings(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: bool
        """
        intervals.sort()

        for i in range(1, len(intervals)):
            if intervals[i].start < intervals[i-1].end:
                return False

        return True       

B = Solution()
print B.canAttendMeetings([Interval(20,30),Interval(25,30)])  

http://ideone.com/OXZ8Lj

相关问题 更多 >