python - 一个函数可以在同一个类中使用另一个函数吗?
问题描述
我想减少我的代码,并想创建一个从另一个类收集内容的函数,然后将我未来的函数引用到“content_collector”,以便能够访问变量(note_input、title_lable、...)。
首先,如问题所述,函数可以访问其他函数中的变量吗?
我还尝试将它们设为全局变量,但我收到 {SyntaxError: name 'note_input' is assigned to before global declaration}
否则,我尝试在函数之外但在类内创建变量,但我认为存在继承问题,因为无法识别“自我”。
class Functions:
def content_collector(self):
note_input = self.note_entry.get("1.0", "end-1c")
title_label = self.title_entry.get()
author_label = self.author_entry.get()
year_label = self.year_entry.get()
others_label = self.others_entry.get()
global note_input, title_label, author_label, year_label, others_label
def file_saveas(self):
dic = {"title": title_label,
"author": author_label,
"year": year_label,
"other": others_label,
"note": note_input}
class EntryWidgets(Functions):
def __init__(self, master):...
与往常一样,非常感谢您提供的有用答案!
解决方案
[..] 函数可以访问其他函数中的变量吗?
不可以。变量只能从其范围内访问。在您的情况下content_collector
,您的变量属于该函数的本地范围,并且只能从该函数内访问。除了它们的作用域之外,变量还有一个生命周期;它们仅在函数执行时存在。虽然file_saveas
执行content_collector
不执行,因此此时变量不存在。
至于您的 SyntaxError:正如它所说,您在为变量赋值后尝试使变量全局化。您需要将该global
语句移至content_collector
方法的开头。即使那样,这些名称也只有在至少执行一次后才能知道(因为只有这样,这些名称才能在语句content_collector
的本地函数范围之外使用)。global
在调用file_saveas
之前调用content_collector
会导致 NameError。
除了将变量设置为全局变量之外,您还可以将它们设置为实例变量,例如在__init__
方法中,或者让content_collector
它们返回这些值,例如:
class Functions:
def content_collector(self):
dic = {"note": self.note_entry.get("1.0", "end-1c"),
"title": self.title_entry.get(),
"author": self.author_entry.get(),
"year": self.year_entry.get(),
"other": self.others_entry.get()}
return dic
def file_saveas(self):
dic = self.content_collector()
推荐阅读
- swift - 带有条件泛型的 Swift 泛型类和扩展
- resize - tf.keras.layers.experimental.preprocessing.Resizing 的替代方案,适用于嵌入式系统 (ARM6)
- node.js - 从子集合中搜索包含来自父子集合的关键字
- java - 我尝试使用 ASM 将 Activity 的类名替换为 SimpleRemapper,但在 proguard apk 中找不到该类
- powerapps - powerapps解决方案中的环境变量错误
- ajax - 快速加载ajax响应
- python - Python解决ODE
- ruby-on-rails - Rails 使用日期和时间、纬度和经度进行搜索
- influxdb - 是否可以在 Influxdb 中获得聚合数据的百分位数?
- amazon-web-services - 我们可以阻止 aws 代码提交存储库中的特定分支吗