0

有时__init__我已经有了应该成为的实例,self我只是想将它设置为那个。
最简单的情况是用于初始化 a 的参数Foo本身就是 a Foo
Foo(Foo(x)) == Foo(x)就像set({1, 2}) == {1, 2}。)
在这个例子中是case_trivial。但也有case_variadic

目前我必须自己设置每个属性。有没有办法在一行中做到这一点?

from variadic_foo_operations import foo_addition, foo_multiplication


class Foo(object):

    def __init__(self, arg=None, addends=None, factors=None):

        case_arg = arg is not None
        case_normal = case_arg and type(arg) == int
        case_trivial = case_arg and type(arg) == Foo

        case_add = addends is not None
        case_multiply = factors is not None
        case_variadic = case_add or case_multiply

        if case_normal:
            self.bar = arg
            self.double_bar = 2 * arg
        elif case_trivial:
            the_foo_i_want = arg
        elif case_variadic:
            operation = foo_addition if case_add else foo_multiplication
            operands = addends if case_add else factors
            current_foo = Foo(0) if case_add else Foo(1)  # neutral element
            for operand_foo in operands:
                current_foo = operation(current_foo, operand_foo)
            the_foo_i_want = current_foo

        if case_trivial or case_variadic:
            # What I would like:
            self = the_foo_i_want
            # What I have to do instead:
            self.bar = the_foo_i_want.bar
            self.double_bar = the_foo_i_want.double_bar
4

1 回答 1

0

在这里找到答案:如何将一个对象的所有属性复制到另一个对象

self.__dict__ = the_foo_i_want.__dict__.copy()
于 2020-07-19T18:58:10.180 回答