我用一个可选的部分/类创建了一个Python包。当我使用这个可选部分(OptClass)时,我必须更改一个类(ExampleClass)的继承。现在我使用这个代码:
if use_option :
_opt_class = __import__('package.my_module', globals(), locals(), ['OptClass']).OptClass
else :
_opt_class = object # do not use the optional class
....
class ExampleClass(base_module.BaseHandler, _opt_class):
....
有没有别的Python式的方法来解决这个问题?例如使用动态继承或layzy加载,或者。。。?在
我可能会使用类装饰器:
在这种情况下,{cd2>你可以写很多。在
我会考虑显式地建模这种模块化。您提到了OAuth2,因此为了这个示例,我假设您要添加的功能是使用该协议进行身份验证。在
然后你会有像这样的文件:
authmodule.py
^{pr2}$exampleclass.py
main.py
显然,这可以有点不同的实现,比如将样板从
ExampleClass
移到DummyAuthModule
。(由于不确定可能继承的类是如何使用的,因此无法确定是否确定。)看起来您想基于
use_option
向ExampleClass
添加一些额外的行为。我只需要编写两个类(一个派生自另一个添加了额外行为的类),然后使用一个泛型名称来指向依赖于use_option
的一个类:这样,您甚至不需要在
ExtendedExampleClass
中添加额外的功能:它已经全部在OptClass
中了。在(也许这就是millimoose提到的策略模式;我不太清楚。)
相关问题 更多 >
编程相关推荐