从python中的变量类继承

时间:2018-08-25 22:23:48

标签: python python-3.x inheritance

我有一个继承自bar的foo类。但是,我还希望在初始化foo时具有从墙继承而不是从bar继承的选项。我在想这样的事情:

class Foo():
    def __init__(self, pclass):
        self.inherit(pclass)
        super().__init__()

Foo(Bar) # child of Bar
Foo(Wall) # child of Wall

这在Python中可行吗?

1 个答案:

答案 0 :(得分:3)

这实际上并不容易,因为在执行类块时(而不是在创建实例时)定义了类。

一种流行的设计模式是将通用代码放入mixin

class FooMixin:
    # stuff needed by both Foo(Bar) and Foo(Wall)

class FooBar(FooMixin, Bar):
    ...

class FooWall(FooMixin, Wall):
    ...

然后您可以使用某种工厂功能:

def make_foo(parent, *init_args, **init_kwargs):
    if parent is Bar:
        Foo = FooBar
    elif parent is Wall:
        Foo = FooWall
    return Foo(*init_args, **init_kwargs)