Python-在类函数内调用函数

标签 python

我有一个运行多个函数的类。其中之一是在屏幕上绘制一个物体。我有另一个函数可以更新对象的状态,并且根据修改后的状态,我必须更改对象的颜色。如何在更新状态的函数内调用绘制形状的函数。代码如下所示:

 class TrackCircuit:
     def __init__(self, id, name, state):
         self.id = id
         self.name = name
         self.state = state

     def draw(self, pos_x, pos_y, pos_end):
         self.pos_x = pos_x
         self.pos_y = pos_y
         self.pos_end = pos_end
         label_root_x = (pos_x + pos_end) / 2
         label_root_y = offset_top + offset_label
         global tc_width

         if self.state == "undefined":
             tc_color = color_undefined
         elif self.state == "occupied":
             tc_color = color_occupied

         canvas.create_line(pos_x, pos_y, pos_end, pos_y, width=tc_width, fill=tc_color)
         tc_label = Label(root, text="121", font = label_font, bg = label_background, fg = label_color)
         tc_label.place(x=label_root_x, y=label_root_y, anchor=CENTER)

     def update_state(self, state):
         self.state = state

当通过 update_state() 修改状态时,我需要运行 draw()

最佳答案

self 它是当前实例,因此您可以调用它的每个方法并访问每个属性。

因此您只需调用:

self.draw()

所以代码变成:

def update_state(self, state):
    self.state = state
    self.draw()

关于Python-在类函数内调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60039397/

相关文章:

python - 根据最大值的长度从 python 嵌套字典中查找项目?

Python文件练习题

python - 名称 'ImageDataBunch' 未定义

Python SVG 解析器

python - pyTelegramBotAPI - 如何发送消息

python curve_fit 没有给出合理的拟合结果

python - xgboost 中的多类分类(python)

python - 如何在python中对数据进行分组

python - 将数据帧列表附加到python中的数据帧列表

python - 为阅读文档扩展 scipy.stats.rv_continuous 时出现元类错误