Python中MyTime类布尔方法转换报错求助:参数缺失TypeError
问题分析与解决方案
错误原因
你遇到的TypeError是因为将独立函数转为类方法时,参数定义或调用方式不匹配。类方法的第一个参数必须是self(代表调用方法的对象本身),如果方法定义里多写了参数,或者调用时传参数量不对,就会触发这个错误。
另外,要实现t1 <= obj < t2的判断,必须先给MyTime类重载__le__(对应<=)和__lt__(对应<)运算符,否则直接用比较符号会报错。
步骤1:编写独立布尔函数between
先实现独立函数,明确逻辑:接收三个MyTime对象t1、obj、t2,返回t1 <= obj < t2的布尔值。前提是MyTime已经重载了比较运算符:
class MyTime: def __init__(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute self.second = second # 重载<=运算符 def __le__(self, other): if not isinstance(other, MyTime): raise TypeError("只能和MyTime对象比较") self_total = self.hour * 3600 + self.minute * 60 + self.second other_total = other.hour * 3600 + other.minute * 60 + other.second return self_total <= other_total # 重载<运算符 def __lt__(self, other): if not isinstance(other, MyTime): raise TypeError("只能和MyTime对象比较") self_total = self.hour * 3600 + self.minute * 60 + self.second other_total = other.hour * 3600 + other.minute * 60 + other.second return self_total < other_total # 独立布尔函数 def between(t1, obj, t2): # 题目已知t1 <= t2,无需额外判断 return t1 <= obj < t2
调用示例:
t1 = MyTime(9, 0, 0) obj = MyTime(10, 30, 0) t2 = MyTime(12, 0, 0) print(between(t1, obj, t2)) # 输出True
步骤2:转为MyTime类的方法
将函数转为类方法时,obj就是调用方法的对象本身(即self),所以方法只需要接收t1和t2两个参数:
修改MyTime类,添加between方法:
class MyTime: def __init__(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute self.second = second def __le__(self, other): if not isinstance(other, MyTime): raise TypeError("只能和MyTime对象比较") self_total = self.hour * 3600 + self.minute * 60 + self.second other_total = other.hour * 3600 + other.minute * 60 + other.second return self_total <= other_total def __lt__(self, other): if not isinstance(other, MyTime): raise TypeError("只能和MyTime对象比较") self_total = self.hour * 3600 + self.minute * 60 + self.second other_total = other.hour * 3600 + other.minute * 60 + other.second return self_total < other_total # 转为类方法后的between def between(self, t1, t2): return t1 <= self < t2
正确调用方式
t1 = MyTime(9, 0, 0) obj = MyTime(10, 30, 0) t2 = MyTime(12, 0, 0) print(obj.between(t1, t2)) # 输出True
为什么会触发你的错误?
你可能犯了以下其中一个错误:
- 方法定义多写了参数:比如写成
def between(self, t1, t2, t3),但调用时只传了t1和t2,导致缺少t3参数。 - 调用方式错误:比如还是用独立函数的调用方式
between(t1, obj, t2),但此时between已经是类方法,第一个参数需要是self,所以会提示缺少参数。
内容的提问来源于stack exchange,提问作者strangevulture
相关产品推荐
相关产品推荐

