简体   繁体   English

从python中的变量类继承

[英]Inheriting from variable class in python

I have a class foo that inherits from bar. 我有一个继承自bar的foo类。 However I also want to have the option when initializing foo to have it inherit from wall instead of bar. 但是,我还希望在初始化foo时具有从墙继承而不是从bar继承的选项。 I am thinking something like this: 我在想这样的事情:

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

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

Is this possible in Python? 这在Python中可行吗?

It's not really possible easily, because classes are defined at the time of executing the class block, not at the time of creating an instance. 这实际上并不容易,因为在执行类块时定义了类,而不是在创建实例时定义了类。

A popular design pattern to use instead would be to put the common code into a mixin : 代替使用的流行设计模式是将通用代码放入mixin中

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

class FooBar(FooMixin, Bar):
    ...

class FooWall(FooMixin, Wall):
    ...

Then you can use some sort of factory function: 然后,您可以使用某种工厂功能:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM