【问题标题】:Is it possible to inherit from class given as parameter?是否可以从作为参数给出的类继承?
【发布时间】:2020-03-05 20:45:23
【问题描述】:

我有几个类,我将它们视为我的数据的容器(图形表示)。他们都有相同的@staticmethods 例如get_edges()get_vertices()。我想通过给定的参数导入指定的图形类。我现在要做的是:

class Figure:
    def __init__(self, figure_type):
        exec('import figures.' + figure_type.lower())
        self.element = eval('figures.' + figure_type.lower() + '.' + figure_type)()

    def create(self, vertices):
        glBegin(GL_LINES)
        for edge in self.element.get_edges():
            for vertex in edge:
                glColor3fv((0.5,0,0))
                glVertex3fv(vertices[vertex])
        glEnd()

class Cube:

    @staticmethod
    def get_edges():
        return ((0, 1),(0, 3),(0, 4),(2, 1),(2, 3),(2, 7),(6, 3),(6, 4),(6, 7),(5, 1),(5, 4),(5, 7))

我想知道是否有办法得到类似的东西:

class Figure(figure_type):
    def __init__(self, figure_type):

为了能够使用例如self.get_edges() 而不是 self.element.get_edges()。我怎么才能得到它?有没有可能?

【问题讨论】:

  • 在 OOP 中,您将使用工厂模式来创建对象:python-3-patterns-idioms-test.readthedocs.io/en/latest/…
  • 为什么选择这个方案Figure 是否具有所有 figure_type 共有的方法,并且每个 figure_type 具有特定的边和顶点方法?出于某种原因,对象是否需要是 Figure 实例?
  • @wwii 是的,Figure 包含应用于每个 figure_type 的方法。 figure_type 仅包含返回带有边、顶点或曲面的 sets 的方法,以便在 Figure 类中的 OpenGL 中绘制它们。我为什么选择它?好吧,它似乎对我来说具有很好的可读性,也许将来我可以为每个图形添加一些特定的方法,但老实说我是初学者,所以我可能会做更好的设计。目前我尝试在答案中遵循给定的链接,但这些概念在我看来有点高级。
  • @Ethr,摆脱exec 并改用importlib。正如 hspandher 所说,使用工厂模式可能比元类更容易(但元类更复杂,玩起来更有趣)。
  • 更好的设计是将所有图形类型简单地放在一个 single 模块中。定义单独的模块,如 figure.cubefigure.whatever 可以做任何有用的事情,并且会使你想要做的事情变得复杂。

标签: python class inheritance


【解决方案1】:

您的设计看起来像是在制作mixins。这是一个可以动态生成 mixin 的类工厂玩具示例。


figures.py

data = ((0, 1),(0, 3),(0, 4),(2, 1),(2, 3),(2, 7),(6, 3))

class FT:
    @staticmethod
    def ge():
        return data

class FT1:
    @staticmethod
    def ge():
        return [(x*x,y*y) for x,y in data]

def compose(ftype):
    '''Returns a class composed of F and ftype.'''
    return type(f'F_{ftype.__name__}',(F,ftype),{})

some_module.py:

import importlib

class F:
    def __init__(self):
        self.x = 'foo'
    def a(self):
        s = '|'.join(f'{thing}' for thing in self.ge())
        return s
    def b(self):
        return 'baz'

def compose(ftype):
    cls = getattr(importlib.import_module('figures'),ftype)
    return type(f'F_{ftype}',(F,cls),{})


z = compose('FT')()
y = compose('FT1')()

两个对象都有相同的b 方法。

>>> z.b(), y.b()
('baz', 'baz')

两者都有相同的a 方法,使用来自特定ge 方法的数据

>>> print(z.a())
(0, 1)|(0, 3)|(0, 4)|(2, 1)|(2, 3)|(2, 7)|(6, 3)
>>> y.a()
'(0, 1)|(0, 9)|(0, 16)|(4, 1)|(4, 9)|(4, 49)|(36, 9)'

每个对象都有特定的ge 方法

>>> z.ge()
((0, 1), (0, 3), (0, 4), (2, 1), (2, 3), (2, 7), (6, 3))
>>> y.ge()
[(0, 1), (0, 9), (0, 16), (4, 1), (4, 9), (4, 49), (36, 9)]
>>> 

zy 是不同类的实例。

>>> z.__class__, y.__class__
(<class '__main__.F_FT'>, <class '__main__.F_FT1'>)
>>> 

组合类的多个实例。

>>> One = compose(FT)
>>> q,r,s = One(),One(),One()
>>> q,r,s
(<__main__.F_FT object at 0x0000000003163860>,
 <__main__.F_FT object at 0x000000000D334198>,
 <__main__.F_FT object at 0x000000000D334828>)
>>>

如果所有东西都在同一个模块中,那么compose就变成了

def compose(ftype):
    return type(f'F_{ftype.__name__}',(F,ftype),{})

z = compose(FT)
y = compose(FT1)

What is the difference between a mixin and inheritance?


使用抽象基类的类似解决方案。 - G 不能被实例化,除非 ge 被覆盖。

import importlib
import abc

class G(abc.ABC):
    def __init__(self):
        self.x = 'foo'
    def a(self):
        s = '|'.join(f'{thing}' for thing in self.ge())
        return s
    def b(self):
        return 'baz'

    @staticmethod
    @abc.abstractmethod
    def ge():
        pass

# either of these work
def new(ftype):
    cls = getattr(importlib.import_module('figures'),ftype)
    return type(cls.__name__,(cls,G),{})
#def new(ftype):
#    cls = getattr(importlib.import_module('figures'),ftype)
#    return type(cls.__name__,(G,),{'ge':staticmethod(cls.ge)})
#usage
# A = new('FT')

除了特定的 static 方法之外的类似方法只是普通函数并使用上面的 ABC

def FT_ge():
    return ((0, 1),(0, 3),(0, 4),(2, 1),(2, 3),(2, 7),(6, 3))
def other_new(f):
    return type(f.__name__.split('_')[0],(G,),{'ge':staticmethod(f)})
# usage
# B = other_new(FT_ge)

【讨论】:

  • 我不知道任何可能的不利后果 - 请随时提出批评或修改意见。
【解决方案2】:

您可以使用importlib.import_module 来导入模块。但是,建议从基类继承这些类,该基类使用元类来跟踪它的子类并将它们映射到字典中。然后就可以用这个基类作为抽象来与所有子类进行交互Track subclasses in python

【讨论】:

  • 你能展示一个模仿 OP 示例的工作玩具示例吗?
猜你喜欢
  • 2020-10-05
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
相关资源
最近更新 更多