簡體   English   中英

在類中設置變量,並使用python中的方法對其進行更新以在類中重用

[英]Setting a variable in a class and updating it with a method in python to re-use in the class

我正在嘗試在一個類中設置一個變量,然后使用類方法對其進行更新,

class App:
    x = 2
    y = 2

    def __init__(self, master, x, y):
        for i in range(x):
            for j in range(y):
                b = Entry(master)
                b.grid(row=i, column=j)
        Button(text='Add ', command=self.enlarge).grid(row=height,
               column=width)
        Button(text='Remove', command=self.shrink).grid(row=height,
               column=width - 1, sticky="e")

    @classmethod
    def enlarge(cls):
        cls.x += 1

    @classmethod
    def shrink(cls):
        cls.x -= 1 

root = Tk()
app = App(root)
mainloop()

即使方法更新了x,它也不會更新我的init函數中的全局x。

您已經創建了xy作為類變量。 您傳遞給__init__函數的xy只是函數參數,它們既不屬於類也不屬於實例。

現在,如果您確實想在init中訪問x和y類變量,則可以使用selfself.__class__ 但是,請注意,如果您使用與類變量同名的實例變量,並且嘗試使用self訪問它們,那么將首先選擇實例變量,只有當未找到相同名稱的實例變量時,才考慮使用類變量。

我用您發布的代碼創建了一個更簡單的示例,以顯示如何在init函數中訪問類變量。 在下面檢查:

class App:
    x = 2
    y = 2

    def __init__(self):
        for i in range(self.__class__.x):
            for j in range(self.__class__.y):
                print ("%s %s" %(i,j))

    @classmethod
    def enlarge(cls):
        cls.x += 1

    @classmethod
    def shrink(cls):
        cls.x -= 1

app = App()

我嘗試過一點更改您的代碼。 首先,當更改類“ App”中的x時,由於不重新加載窗口,因此不會自動附加一行。 我假設您有另一個功能可以在x更改時重新加載窗口。 如果沒有,您可以再次調用init ()。

現在更改后的代碼(python3):

from tkinter import Entry, Button
import tkinter as tk

class App:
    x = 2
    y = 2

    def __init__(self, master):
        self.master = master
        self.topFrame = tk.Frame(master)
        self.topFrame.grid(row = 0, columnspan = 2)
        for i in range(self.x):
            for j in range(self.y):
                b = Entry(self.topFrame)
                b.grid(row=i, column=j)
        Button(self.topFrame, text='Add ', command=self.enlarge).grid(row=2,
               column=2)
        Button(self.topFrame, text='Remove', command=self.shrink).grid(row=2,
               column=2 - 1, sticky="e")

    def enlarge(self):
        self.x += 1
        self.topFrame.destroy()
        self.__init__(self.master)

    def shrink(self):
        self.x -= 1
        self.topFrame.destroy()
        self.__init__(self.master)

root = tk.Tk()
app = App(root)
tk.mainloop()

請注意,調用了init ()方法來重新加載窗口。 基本上,x和y參數已從init ()方法中刪除,並成為類“ App”的屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM