延迟加载/配置要继承的类

2024-10-02 22:37:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我用一个可选的部分/类创建了一个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加载,或者。。。?在


Tags: 代码importpackageifusemyelseclass
3条回答

我可能会使用类装饰器:

def optional_inherit(cls):
    if use_option:
        from package.my_module import OptClass
        class ExampleClassWithOptClass(cls, OptClass):
            pass
        return ExampleClassWithOptClass
    else:
        return cls

...

@optional_inherit
class ExampleClass(base_module.BaseHandler):
    ...

在这种情况下,{cd2>你可以写很多。在

我会考虑显式地建模这种模块化。您提到了OAuth2,因此为了这个示例,我假设您要添加的功能是使用该协议进行身份验证。在

然后你会有像这样的文件:

authmodule.py

import oauth2client
# ...

class OAuth2Module(object):
    # ...

exampleclass.py

^{pr2}$

main.py

# this is where ExampleClass is created
if use_option:
    # the optional dependency only really gets pulled in here
    from authmodule import AuthModule
    example_obj = ExampleClass(AuthModule())
else:
    example_obj = ExampleClass(None)

# ...
example_obj.foo()

显然,这可以有点不同的实现,比如将样板从ExampleClass移到DummyAuthModule。(由于不确定可能继承的类是如何使用的,因此无法确定是否确定。)

看起来您想基于use_optionExampleClass添加一些额外的行为。我只需要编写两个类(一个派生自另一个添加了额外行为的类),然后使用一个泛型名称来指向依赖于use_option的一个类:

from package.my_module import OptClass

class SimpleExampleClass(base_module.BaseHandler):
    pass

class ExtendedExampleClass(SimpleExampleClass, OptClass):
    pass

ExampleClass = ExtendedExampleClass if use_option else SimpleExampleClass

这样,您甚至不需要在ExtendedExampleClass中添加额外的功能:它已经全部在OptClass中了。在

(也许这就是millimoose提到的策略模式;我不太清楚。)

相关问题 更多 >