【问题标题】:python object building using multi-inheritance使用多继承的python对象构建
【发布时间】:2019-11-15 23:08:43
【问题描述】:

我想动态构建一个对象,它允许使用基于多重继承的任何方式混合类属性。这是预期的行为。这些类是数据类,所以其中不会有很多方法,主要是数据属性。

class Foo():
    def bar(self, x):
            return x

class FooA(Foo):
    def bar(self, x):
        p = super().bar(x)
        p += __class__.__name__
        return p

class FooB(Foo):
    def bar(self, x):
        p = super().bar(x)
        p += __class__.__name__
        return p

class FooC(FooA, FooB):
    def bar(self, x):
        p = super().bar(x)
        p += __class__.__name__
        return p

f = FooC()
f.bar('S') # SFooBFooAFooC

但是这段代码在光天化日之下违反了 DRY 原则,因此如果当前类中没有特殊操作,我想完全避免使用 bar 方法。

理想情况下我想要类似的东西

@bar_wrapper
class FooA(Foo):
    pass

# OR

class FooA(Foo):
    __metaclass__ = BarBase

而不是这个完整的实现

class FooA(Foo):
    def bar(self, x):
        p = super().bar(x)
        p += __class__.__name__
        return p

基本上有没有办法通过装饰器或元类(我能想到的两个选项)提取多级继承类中的中间层类信息?任何人都知道如何做到这一点?

【问题讨论】:

    标签: python class object inheritance data-class


    【解决方案1】:

    编写一个类装饰器,将bar 方法添加到类中:

    def bar_wrapper(cls):
        def bar(self, x):
            p = super(cls, self).bar(x)
            p += cls.__name__
            return p
    
        bar.__module__ = cls.__module__
        bar.__qualname__ = '{}.{}'.format(cls.__qualname__, bar.__name__)
    
        cls.bar = bar
        return cls
    
    class Foo():
        def bar(self, x):
            return x
    
    @bar_wrapper
    class FooA(Foo):
        pass
    
    @bar_wrapper
    class FooB(Foo):
        pass
    
    @bar_wrapper
    class FooC(FooA, FooB):
        pass
    
    f = FooC()
    print(f.bar('S')) # SFooBFooAFooC
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 2019-12-29
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多