複数のプロパティを個別に参照せずにPythonで設定するにはどうすればよいですか? 以下は私の解決策です。
class Some_Class(object):
def __init__(self):
def init_property1(value): self.prop1 = value
def init_property2(value): self.prop2 = value
self.func_list = [init_property1, init_property2]
@property
def prop1(self):
return 'hey im the first property'
@prop1.setter
def prop1(self, value):
print value
@property
def prop2(self):
return 'hey im the second property'
@prop2.setter
def prop2(self, value):
print value
class Some_Other_Class(object):
def __init__(self):
myvalues = ['1 was set by a nested func','2 was set by a nested func']
some_class= Some_Class()
# now I simply set the properties without dealing with them individually
# this assumes I know how they are ordered (in the list)
# if necessary, I could use a map
for idx, func in enumerate(some_class.func_list):
func(myvalues[idx])
some_class.prop1 = 'actually i want to change the first property later on'
if __name__ == '__main__':
test = Some_Other_Class()
これは、ユーザー定義の値で初期化するプロパティが多数ある場合に必要になりました。そうしないと、私のコードは、各プロパティを個別に設定する巨大なリストのように見えます (非常に面倒です)。
多くの人が以下に良い答えを持っていることに注意してください。私は良い解決策に達したと思います. これは主に質問を明確に述べようとする再編集です。しかし、誰かがより良いアプローチを持っている場合は、共有してください!