python - 结构类未定义尚未使用?
问题描述
这是来自 tkinter 游戏 Random 和 tkinter 模块的代码的一部分已被导入。我的问题是——
1. 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*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)
2.这行代码中发生了什么:
root.canvas = canvas.canvas = canvas
class Struct: pass
canvas.data = Struct()
- 由于没有定义类,canvas.data._______ 是如何使用的?
解决方案
问题:未定义的结构类尚未使用?
你错了,class Struct
是定义的。
此行定义了一个有效对象:
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
使用预定义的对象class Struct.__init__
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
推荐阅读
- python - 如何正确切分for循环?
- r - 不同长度的每个因子级别的聚合数字
- java - REST POST 用于身份验证的哪个异常失败
- c# - Browser not Reading client certificate
- android - 如何在视图中存储对另一个视图的引用?
- php - Authentication failure trying to upload Vimeo video
- reactjs - Expo Show AsyncStorage data 重启应用后
- unit-testing - "module cannot be found locally" when running detailed-0.9 test suite with Haskell Stack
- javascript - Regex to replace special characters with space from English and Arabic language string using javascript
- css - Angular - 使用 regex 和 css 使用 ngIf 和 ngFor 有条件地格式化标签