Python:如何将属性从一个函数调用到另一个函数?

2024-10-01 00:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

from tkinter import *
import os

class App:

    charprefix = "character_"
    charsuffix = ".iacharacter"
    chardir = "data/characters/"
    charbioprefix = "character_biography_"

    def __init__(self, master):
        self.master = master
        frame = Frame(master)
        frame.pack()

        # character box
        Label(frame, text = "Characters Editor").grid(row = 0, column = 0, rowspan = 1, columnspan = 2)
        self.charbox = Listbox(frame)
        for chars in []:
            self.charbox.insert(END, chars)
        self.charbox.grid(row = 1, column = 0, rowspan = 5)
        charadd = Button(frame, text = "   Add   ", command = self.addchar).grid(row = 1, column = 1)
        charremove = Button(frame, text = "Remove", command = self.removechar).grid(row = 2, column = 1)
        charedit = Button(frame, text = "    Edit    ", command = self.editchar).grid(row = 3, column = 1)

        for index in self.charbox.curselection():
            charfilelocale = self.charbox.get(int(index))
            charfile = open(app.chardir + app.charprefix + charfilelocale, 'r+')
            charinfo = self.charfile.read().splitlines(0)

现在我想知道的是,如果我要在另一个函数中调用charinfo,我应该怎么调用它?我使用的是python3.3和应用程序charinfo或者自我.charinfo别工作。如果我的代码不正确,你能帮我纠正一下吗?提前谢谢。在


Tags: 代码textimportselfmastercolumnbuttonframe
1条回答
网友
1楼 · 发布于 2024-10-01 00:34:10

您当前的实现将其声明为局部变量,因此在外部可访问。 要实现这一点,需要在self.charinfo上进行赋值:

当您想从其他地方访问charinfo
-self.charinfo在类定义中工作,并且
-app.charinfo在类/实例之外工作

for index in self.charbox.curselection():
    charfilelocale = self.charbox.get(int(index))
    charfile = open(app.chardir + app.charprefix + charfilelocale, 'r+')
    # notice the self.charinfo here
    self.charinfo = self.charfile.read().splitlines(0)

最好确保属性self.charinfo在循环之外可用,以避免在循环0次时出错

^{pr2}$

相关问题 更多 >