传递实例以在同一个 class 中运行

Passing instances to function within the same class

假设我有这样的东西:

class MyClass_1(object):
    def __init__(self, name, x1, x2, x3):
        self.name = name
        self.x1 = x1
        self.x2 = x2
        self.x3 = x3

    def run(self):
        if self.name == 'func1':
            result = self.func1()
        elif self.name == 'func2':
            result = self.func2() 
        return result

    def func1(self):
        return Myclass_2(x1=self.x1, x2=self.x2, x3=self.x3).func() 

    def func2(self):
        return Myclass_3(x1=self.x1, x2=self.x2, x3=self.x3).func() 


class MyClass_2(object):
    def __init__self, **kwargs): 
        self.__dict__.update((k, v) for k, v in kwargs.items())

    def func(self):
        return #do something to the interested instances 

class MyClass_3(object):
    def __init__self, **kwargs): 
        self.__dict__.update((k, v) for k, v in kwargs.items())

    def func(self):
        return #do something to the interested instances 

如何跳过显式初始化 MyClass_2MyClass_3

也就是说,不必写 Myclass_2(x1 = self.x1, x2 = self.x2, x3 = self.x3).func() 有没有办法传入我为 MyClass_1 初始化的所有实例以节省冗余?

如果你想传递一组东西,把它放在一个容器里。如果那些东西需要命名,把它们放在一个映射中:

def __init__(self, name, x1, x2, x3):
    self.name = name
    self.x = {
        'x1': x1,
        'x2': x2,
        'x3': x3,
    }

现在您每次都可以干净地使用该映射:

def func1(self):
    return Myclass_2(**self.x).func()

您可能要考虑的另一件事是删除 run 中的冗余:

def run(self):
    return getattr(self, self.name)()

您实际上可以更进一步,将函数名称映射到具有 func 的对象。为此,您需要定义 MyClass_1 after MyClass_2MyClass_3:

class MyClass_1(object):
    delegates = {
        'func1': MyClass_2,
        'func2': MyClass_3
    }

    def __init__(self, name, x1, x2, x3):
        self.name = name
        self.x = {
            'x1': x1,
            'x2': x2,
            'x3': x3,
        }

    def run(self):
        return self.delegates[self.name](**self.x).func()