在带有一些参数的方法中调用方法

问题描述 投票:0回答:1

我正在做面向对象的编程并且对它很陌生。我已经定义了类和方法,但是当我尝试调用一个将一些参数带入另一个方法的方法时,我遇到了一些问题。它给了我:NameError: name 'time' is not defined .

下面是我的代码片段。

    def completed_transfer_tasks(self, time: int):

        if self.transfer_equipment is not None:

            completed_transfer_task_ids = []

            for equipment in self.transfer_equipment:

                if equipment.transfer_tasks is not None:

                    for task in equipment.transfer_tasks:

                        if time - task.start_time >= task.min_transfer_duration:
                            completed_transfer_task_ids.append(task.id)

            return completed_transfer_task_ids

        else:

            print('Stage has TransferEquipment None')

我正在尝试在另一个方法中使用此方法,如下所示:

 def transfer_task_passed_minimum_from_unassigned_production_tasks(self):

        production_task_ids = self.unassigned_production_tasks_in_stage2and3()
        transfer_task_ids = self.completed_transfer_tasks(time)

        for id in production_task_ids:
            if id in transfer_task_ids:
                return id

        return None

当我尝试像下面这样调用这个方法时,

stage2 = Stage(2, [equipment1], [equipment2, equipment3])

if __name__ == '__main__':
    stage2.completed_transfer_tasks(70)
    x = stage2.transfer_task_passed_minimum_from_unassigned_production_tasks()
    print(x)

我不确定我是否在正确意义上引用该方法?

我最初尝试给出时间参数,但这不是预期的,因为它应该被定义为一个参数。

我想我缺少一些我无法纠正的调用方法的语法。

python function oop methods nameerror
1个回答
0
投票

这是因为在

time
函数的范围内没有名为
transfer_task_passed_minimum_from_unassigned_production_tasks
的对象。 你应该先绑定一个对象到这个名字然后你可以使用它。


 def transfer_task_passed_minimum_from_unassigned_production_tasks(self):

        production_task_ids = self.unassigned_production_tasks_in_stage2and3()
        time = ... # something that it should be
        transfer_task_ids = self.completed_transfer_tasks(time)

        for id in production_task_ids:
            if id in transfer_task_ids:
                return id

        return None

或者你可以直接传递

time
参数:

 def transfer_task_passed_minimum_from_unassigned_production_tasks(self):

        production_task_ids = self.unassigned_production_tasks_in_stage2and3()
        transfer_task_ids = self.completed_transfer_tasks(...)  # whatever it should be

        for id in production_task_ids:
            if id in transfer_task_ids:
                return id

        return None

另一方面,您可以将

time
设置为类或对象变量,并在需要的地方使用它。

    def completed_transfer_tasks(self, time: int):
        self.time = time
        ...

然后这样使用:

 def transfer_task_passed_minimum_from_unassigned_production_tasks(self):

        production_task_ids = self.unassigned_production_tasks_in_stage2and3()
        transfer_task_ids = self.completed_transfer_tasks(self.time)

        for id in production_task_ids:
            if id in transfer_task_ids:
                return id

        return None

© www.soinside.com 2019 - 2024. All rights reserved.