有时__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