python - 更改构建器方法

标签 python kivy

如何更改 Builder 类方法行为? 比方说,我想稍微更改 load_string 方法,例如,以便在调用此方法时打印“Hi”。

我在BuilderBase类中找到了这个方法(链接如下)。我可以子类化 BuilderBaseBuilder 吗? 我尝试以这种方式子类化Builder:

from kivy.app import App
from kivy.lang import Builder

KV = """
Label
    text: 'test'
"""

class New_builder(Builder):
  def load_string(self, *l, **kw):
    super().load_string(*l, **kw)
    print('hi')


class MyApp(App):
    def build(self):
        return New_builder.load_string(KV)


MyApp().run()

我明白了

 Traceback (most recent call last):
   File "main.py", line 9, in <module>
     class New_builder(Builder):
 TypeError: __init__() takes 2 positional arguments but 4 were given

https://github.com/kivy/kivy/blob/master/kivy/lang/builder.py

最佳答案

假设您不想完全更改原始功能,而是在其基础上构建又名装饰它。您可以混合使用装饰器模式和猴子修补,如下所示:

from kivy.app import App
from kivy.lang import Builder

KV = """
Label
    text: 'test'
"""


# Create a decorator function that will add new functionality
def new_func(func):

    def inner(*args, **kwargs):
        result = func(*args, **kwargs)
        # your custome code can go before or after the call to the original function
        print("Hi")
        return result
    return inner

#Using monkeypatching monkey patch the Builder object to use the newly decorated function
Builder.load_string = new_func(Builder.load_string)


class MyApp(App):
    def build(self):
        return Builder.load_string(KV)


MyApp().run()

这是因为正如我所指出的,Builder 不是一个类,而是类 BaseBuilder 的一个对象,因此不可能从它继承,这就是我们的原因将旧函数替换为我们新创建的函数。另请注意,如果在导入库内使用 Builder 对象方法 load_string,我的意思是在导入期间执行一些使用 load_string 的代码解决方案不会影响该代码,因为修补是在导入后完成的。

话虽这么说,该示例已经过检查并且正在运行。

关于python - 更改构建器方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57175195/

相关文章:

python - 在 kvlang 中访问 Kivy 布局大小

android - 我无法为 Android 构建 buildozer

python - 如何在 Mac 上使用 pipenv?

python - 卡在 Python 3 中的错误(异常、循环)

python - python setup.py sdist和自定义设置关键字不能一起使用

python - 在 try block 中获取

python-3.x - Windows 10 Kivy 安装指南

python - 构建 kivy 应用程序时出错 : ModuleNotFoundError: No module named 'typing_extensions'

python - Kivy:获取固定大小的小部件以显示在窗口中央

javascript - 用于 JavaScript 生成的 URL 的 Python Web 爬虫