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
draw()
当状态被修改时,我需要运行update_state()
.
解决方案
self
它是当前实例,因此您可以在每个方法上调用它并访问每个属性。
因此,您只需要调用:
self.draw()
于是代码变成了:
def update_state(self, state):
self.state = state
self.draw()
推荐阅读
- html - 如何在新行中换行
- python - 如何在 pandas 数据框中的某个范围内对每第 n 行进行采样?
- python - 使用 Erlang C 求解调用次数
- python - 在 Python3 中使用大型机数据集
- automation - 单击多个窗口 - Hammerspoon 中的 AutoHotKey 等效项
- python - 具有插件层次结构的跨模块的 Python 日志记录
- sql - 更新一行以实现错误捕获
- react-native - npm 错误!代码 ENOTEMPTY npm 错误!尝试安装 Expo 以进行本机反应时重命名系统调用
- python - 为什么 GridSearchCV 将 NAN 显示为分数?
- octave - 无法在八度函数中返回复数