简体   繁体   English

为子类自动生成方法

[英]Auto-generate methods for subclasses

I have a few dozen classes.我有几十节课。 Here are two of them:这是其中的两个:

class Class_A(ClassABC):

    def __init__(self):
        super().__init__()

    def from_B(self, b):
        #do stuff

    def from_C(self, c):
        #do stuff

    #...

    def to_B(self):
        rt = Class_B()
        rt.from_A(self)
        return rt

    def to_C(self):
        rt = Class_C()
        rt.from_A(self)
        return rt

    #...

class Class_B(ClassABC):

    def __init__(self):
        super().__init__()

    def from_A(self, a):
        #do stuff

    def from_C(self, c):
        #do stuff

    def to_A(self):
        rt = Class_A()
        rt.from_B(self)
        return rt

    def to_C(self):
        rt = Class_C()
        rt.from_B(self)
        return rt

    #...

 #class Class_C, Class_D, Class_E, etc,

and here is the ABC:这是ABC:

class ClassABC(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def __init__(self):
        #do stuff

The problem I have is that all the to_* methods in the subclasses follow the same exact pattern, and it becomes tedious to implement them.我遇到的问题是子类中的所有to_*方法都遵循相同的模式,实现它们变得乏味。 I would like to automatically generate them in the ClassABC if possible, but so far I have failed.如果可能的话,我想在ClassABC中自动生成它们,但到目前为止我失败了。 I also tried creating a class decorater for the subclasses, but that didn't work either.我还尝试为子类创建一个 class 装饰器,但这也不起作用。 I have, however, managed to auto generate the methods in each subclass using exec(), but I rather have the ABC generate them or use class decoraters.然而,我已经设法使用 exec() 自动生成每个子类中的方法,但我宁愿让 ABC 生成它们或使用 class 装饰器。 Is there a way to do this?有没有办法做到这一点?

Note: all the classes are in their own separate module注意:所有类都在它们自己的单独模块中

First of all, your to_* methods aren't going to work because you need to explicitly include self at the beginning of the argument list to be able to use it in the method body.首先,您的to_*方法将不起作用,因为您需要在参数列表的开头显式包含self才能在方法主体中使用它。 Secondly, I'd go with something akin to JBernardo's suggestion.其次,我会使用类似于 JBernardo 的建议的 go 。

def to_class(self, cls):
    rt = cls()
    rt.from_class(self.__class__)
    return rt

def from_class(self, cls):
    #do stuff, with different things happening based on what class cls is; this may be a good place to use a dict of functions with the class or classname as keys

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

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