Skip to main content
 首页 » 编程设计

python 无法识别我的函数

2024年10月01日7TianFang

我有一个奇怪的问题,当我运行我的代码时,我的程序会给我这个错误消息:

Traceback (most recent call last): 
   File "\\srv-fons-02\USV_Home$\6357\inf\Phyton\classes test 1.py", line 38, in <module> 
     time = Time(7, 61, 12)   File "\\srv-fons-02\USV_Home$\6357\inf\Phyton\classes test 1.py", line 8, in __init__ 
     self = int_to_time(int(self)) NameError: name 'int_to_time' is not defined 

它告诉我函数 int_to_time 没有定义,而它是。我也只在我的 __init__ 中遇到这个问题,而不是在我使用它的其他地方(例如 __add__ 中使用的 add_time )。我不知道为什么它确实适用于某些功能。我已经尝试在 __init__ 中取消 int_to_time() 并且即使我使用 __add__ 也没有收到错误消息)。

如果有人能帮助我,那就太好了,因为我被卡住了。

这是我的代码:

class Time: 
    def __init__(self, hour=0, minute=0, second=0): 
        self.hour = hour 
        self.minute = minute 
        self.second = second 
        if not 0 <= minute < 60 and 0<= second < 60: 
            self = int_to_time(int(self)) 
 
    def __str__(self): 
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second) 
 
    def __int__(self): 
        minute = self.hour * 60 + self.minute 
        second = minute * 60 + self.second 
        return int(second) 
 
    def __add__(self, other): 
        if isinstance(other, Time): 
            return self.add_time(other) 
        else: 
            return self.increment(other) 
 
    def __radd__(self, other): 
        return other + int(self) 
 
 
    def add_time(self, other): 
        seconds = int(self) + int(other) 
        return int_to_time(seconds) 
 
    def increment(self, seconds): 
        seconds += int(self) 
        return int_to_time(seconds) 
    """Represents the time of day. 
    atributes: hour, minute, second""" 
 
time = Time(7, 61, 12) 
 
time2 = Time(80, 9, 29) 
 
def int_to_time(seconds): 
    time = Time() 
    minutes, time.second = divmod(seconds, 60) 
    time.hour, time.minute = divmod(minutes, 60) 
    return time 
 
 
print(time + time2) 
print(time + 9999) 
print(9999 + time) 

请您参考如下方法:

int_to_time 的调用是在 看到定义之前进行的,这就是问题所在。

在定义 int_to_time 之前初始化两个 Time 对象:

time = Time(7, 61, 12) 
 
time2 = Time(80, 9, 29) 
 
def int_to_time(seconds): 
    time = Time() 

在 Time.__init__ 中,您在特定条件后调用 int_to_time。如果满足该条件,对 int_to_time 的调用将失败。

只需将初始化移到定义就足够了。由于 int_to_time 似乎也与您的 Time 类密切相关,因此将它定义为该类的 @staticmethod 并不是一个坏主意,并且抛开对何时定义的所有担忧。