簡體   English   中英

從python中的變量類繼承

[英]Inheriting from variable class in python

我有一個繼承自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中可行嗎?

這實際上並不容易,因為在執行類塊時定義了類,而不是在創建實例時定義了類。

代替使用的流行設計模式是將通用代碼放入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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM