Python 结构类未定义,是否已使用?
这是tkinter游戏代码的一部分 已导入Random和tkinter模块。 我的问题是- 一,。 Struct类只进行了初始化,但没有定义,只是简单地传递了它,然后就被使用了Python 结构类未定义,是否已使用?,python,oop,Python,Oop,这是tkinter游戏代码的一部分 已导入Random和tkinter模块。 我的问题是- 一,。 Struct类只进行了初始化,但没有定义,只是简单地传递了它,然后就被使用了 def run(rows, cols): # create the root and the canvas global canvas root = Tk() margin = 5 cellSize = 15 canvasWidth = 2*margin + cols*cellSize canvasHeight = 2*
def run(rows, cols):
# create the root and the canvas
global canvas
root = Tk()
margin = 5
cellSize = 15
canvasWidth = 2*margin + cols*cellSize
canvasHeight = 2*margin + rows*cellSize+100
canvas = Canvas(root, width=canvasWidth, height=canvasHeight)
canvas.pack()
# Store canvas in root and in canvas itself for callbacks
root.canvas = canvas.canvas = canvas
# Set up canvas data and call init
class Struct: pass
canvas.data = Struct()
canvas.data.margin = margin
canvas.data.cellSize = cellSize
canvas.data.canvasWidth = canvasWidth
canvas.data.canvasHeight = canvasHeight
canvas.data.rows = rows
canvas.data.cols = cols
canvas.data.canvasWidth = canvasWidth
canvas.data.canvasHeight = canvasHeight
canvas.data.player1Score = 0
canvas.data.player2Score = 0
canvas.data.inGame = False
init()
# set up events
root.bind("<Key>", keyPressed)
timerFired()
# and launch the app
root.mainloop() # This call BLOCKS (so your program waits until you close the window!)
run(40,40)
类结构已定义
此行定义了一个有效的对象:
class Struct: pass
以下两个示例是等效的强>
Struct
成为canvas
属性,然后使用属性扩展对象
margin = 5
# Define the object
class Struct: pass
# Instantiate the object `Struct`
# Assign the reference to the object `Struct` to the attribute `.data`
canvas.data = Struct()
# Assing the value `margin` to the attribute `.margin` of the object `Struct`
canvas.data.margin = margin
# Access the attribute `.margin` in the object `Struct`
print(canvas.data.margin)
# >>> 5
Struct
使用预定义的类结构
margin = 5
# Define the object
class Struct:
def __init__(self, margin):
self.margin = margin
# Instantiate the object `Struct`
# Pass the value `margin` to it
# Assign the reference to the object `Struct` to the attribute `.data`
canvas.data = Struct(margin)
# Access the attribute `.margin` in the object `Struct`
print(canvas.data.margin)
# >>> 5
请修复已发布代码的缩进。感谢您的回答,但是我们如何访问画布的属性“.data”?@AppleKrumble:“访问画布的属性
.data
”*:canvas.data
。不,我的意思是“canvas”是“canvas”类的对象,它是“Tkinter”模块的一部分。因此,“canvas.data”是对象“canvas”的一个属性,而对象“canvas”又变成了“Struct”类的对象?@AppleKrumble:你是在问如何才能在这里.data
向tkinter类canvas
实例对象,这里canvas
添加一个属性?是的,有点像这样,在这种情况下会发生什么?
margin = 5
# Define the object
class Struct:
def __init__(self, margin):
self.margin = margin
# Instantiate the object `Struct`
# Pass the value `margin` to it
# Assign the reference to the object `Struct` to the attribute `.data`
canvas.data = Struct(margin)
# Access the attribute `.margin` in the object `Struct`
print(canvas.data.margin)
# >>> 5