首页 > 解决方案 > 结构类未定义尚未使用?

问题描述

这是来自 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()
  1. 由于没有定义类,canvas.data._______ 是如何使用的?

标签: pythonoop

解决方案


问题:未定义的结构类尚未使用?

你错了,class Struct 是定义的。
此行定义了一个有效对象:

class Struct: pass

下面两个例子是等价的!

  1. 空对象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
    
  2. 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
    

推荐阅读