我有以下课程:
class Family:
self.dad = Person("Doug")
self.mom = Person("Jane")
self.family_members = [self.dad, self.mom]
def wrap_family_members(self, wrapper_class):
for family_member in self.family_members:
# What do I put here?
# family_member = wrapper_class(family_member) <- this doesn't work.
# family_member is locally scoped within the loop and
# so family_member = ... doesn't update the Family instance attribute
# The behavior I want:
# self.dad = wrapper_class(self.dad)
# self.mom = wrapper_class(self.mom)
# ...
# But I don't want to manually assign these attributes. I want them to be assigned based on what is currently in the list self.family_members
我在上面的评论中解释了这些问题。包装器类可以是向Person对象添加其他功能或方法的任何类。
答案 0 :(得分:0)
您可以使用其他类型的for循环:
for i in range(len(self.family_members)):
self.family_members[i] = wrapper_class(self.family_members[i])