【问题标题】:Python: How do you call an attribute from one function into another?Python:如何将一个函数的属性调用到另一个函数中?
【发布时间】:2013-08-14 06:15:10
【问题描述】:

这是代码:

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,我应该怎么称呼它?我正在使用 Python 3.3,而 app.charinfo 或 self.charinfo 不起作用。如果我的代码不正确,您能帮忙更正一下吗?提前致谢。

【问题讨论】:

  • 你不能调用它,它是一个函数的局部变量,它的作用域在那个函数内部。如果你想在另一个类中使用它,将它声明为一个类变量意味着 instaed charinfo 类型 self.charinfo

标签: python function python-3.x python-3.3


【解决方案1】:

您当前的实现将其声明为局部变量,因此可以在外部访问。 为此,分配需要发生在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次时出错

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

【讨论】:

  • 但现在显示字符串超出范围
  • @PithiratHorvichien 恐怕这可能是您的应用程序特有的。我只是传达了用法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-04
  • 2022-06-17
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多