我使用 user_data_dir 的代码不起作用,它给出了一个错误,指出 'self' 未定义。有人可以向我解释为什么吗?

My code using user_data_dir does not work and it gives an error saying 'self' is not defined. Can someone explain to me why?

以下是我的代码片段。当我尝试 运行 时,错误指出 'self' 未定义。我在网上复制了这段代码,因为我真的不知道如何使用函数user_data_dir。我知道它只用 store = JsonStore('user.json') 就可以工作(我正在使用 Windows 来写这个),但我一直在读到使用函数 user_data_dir 会很有用,因为它是为各种系统创建可写路径的通用函数。如果有人能帮忙解释一下就太好了!

from kivy.storage.jsonstore import JsonStore
from os.path import join

data_dir = getattr(self, 'user_data_dir')
store = JsonStore(join(data_dir,'user.json'))

class Welcome(Screen):
    pass
data_dir = getattr(self, 'user_data_dir')

当您复制此行时,它位于某些 class 函数中的某处:

class Some:
    def func(self):
        data_dir = getattr(self, 'user_data_dir')

Method located inside class in Python receives self 作为第一个参数。

但不是每个对象都有 user_data_dir 属性:正如上面注意到的那样,它是 App 对象属性。你应该这样做:

class MyApp(App):
    def build(self):

        data_dir = getattr(self, 'user_data_dir')
        store = JsonStore(join(data_dir,'user.json'))

        # ...

更新:

您可以将 json 文件的路径存储在应用程序 class 中,并访问应用程序实例以使用 App.get_running_app():

获取此路径
class MyApp(App):
    @property  # see https://www.programiz.com/python-programming/property
    def storage(self):
        return join(self.user_data_dir, 'user.json')

以后在任何你想要的地方:

class SomeClass():
    def some_func(self):
        print('here\'s our storage:', App.get_running_app().storage)