python无法识别我的函数

2024-03-29 01:47:16 发布

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

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

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)

Tags: toselfaddreturntimeinitdefint
1条回答
网友
1楼 · 发布于 2024-03-29 01:47:16

调用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并消除所有关于何时定义的担忧并不是一个坏主意。你知道吗

相关问题 更多 >