python - 是否可以从作为参数给出的类继承?

标签 python class inheritance

我有几个类,我将它们视为数据的容器(图形表示)。它们都有相同的@staticmethod,例如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()。我怎么才能得到它?这可能吗?

最佳答案

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

<小时/>

数字.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>)
>>>
<小时/>

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

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')
<小时/>

类似,除了特定的静态方法只是普通函数并使用上面的 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)

关于python - 是否可以从作为参数给出的类继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58779748/

相关文章:

javascript - typescript :从方法参数中调用方法

java - Android必须实现继承的抽象方法

c# - 自定义属性是否可以在没有继承的情况下暗示其他属性?

python - crontab 不适用于 Centos Docker 容器

python - 在 Python 中查找最小值或最大值的值的索引

Python - 图书馆应该在哪里存储临时文件?

Python POST 请求,无需重新加载页面

c++ - 比较同一类的 2 个对象(覆盖 == 运算符)c++

java - 通过类参数检查的通用类型参数可以被黑客攻击,有更好的方法吗?

java - 如何从另一个继承类调用 super 构造函数?