如何更改 Builder
类方法行为?
比方说,我想稍微更改 load_string
方法,例如,以便在调用此方法时打印“Hi”。
我在BuilderBase
类中找到了这个方法(链接如下)。我可以子类化 BuilderBase
或 Builder
吗?
我尝试以这种方式子类化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/