python 无法识别我的函数

标签 python python-3.x class

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

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 并不是一个坏主意,并且放下所有关于定义何时制定的担忧。

关于python 无法识别我的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42696358/

相关文章:

python - 使用制表符格式化空白

java - 我想使用类中的方法设置和获取实例属性

javascript - TypeScript接口(interface)签名 "(): string"

python - For 循环遍历单个列表中的多个变量

python - 如何绘制 3d 直方图

Python:使用可调用对象而不是本地函数作为装饰器中的包装器

python - 两个不同的 Python 类与同一底层对象共享属性

python - 为什么 jsmin 在 python 子进程中运行时会提前退出?

python - 尝试使用 PyQt5 在两个类之间发送信号以更改 configparser 中的标签

python - 如何从根路径自动重定向?