updating values of class attributes
I have a class like the following:
class MyClass(object):
def __init__(self, input1, input2):
self.attribute1 = [(a1_d1, a1_p1), (a1_d2, a1_p2)]
self.attribute2 = [(a2_d1, a2_p1), (a2_d2, a2_p2), ..., (a2_d10, a2_p10)]
...some other attributes here...
The first coordinate in every pair is some decision/action and the second coordinate is the probability with which that action is chosen. I want to write a function that updates these probabilities for an instance of this class as the program runs. The way probabilities are updated depends on the decision taken previously. For example, I can write functions of the following sort:
def update_probabilities_attribute1(self, decision):
i = 0
for action, current_probability in self.attribute1:
SOME CODE HERE
self.attribute1[i] = (action, new_probability)
i = i + 1
def update_probabilities_attribute2(self, decision):
i = 0
for action, curr开发者_如何学Cent_probability in self.attribute2:
SOME CODE HERE
self.attribute1[i] = (action, new_probability)
i = i + 1
The part SOME CODE HERE is common to two functions. Is there anyway that I can have one function instead of two different ones, which takes self.attribute1 or self.attribute2 as an input and updates it accordingly.
Thanks.
You could use getattr
and relatives:
def update_probabilities(self, attribute_name, decision):
i = 0
attr_value = getattr(self, attribute_name)
for action, current_probability in attr_value:
#SOME CODE HERE
attr_value[i] = (action, new_probability)
i = i + 1
setattr(self, attribute_name, attr_value)
self.attribute = function_name(previous_attribute_value)
Then to get a value:
def function_name(attribute):
#Compute the new value
return new_attribute_value
I guess you could use a lambda
too, instead of calling a function, but it's probably not so reusable.
Since your "attributes" all fundamentally behave the same way and are subject to the same kind of processing, just put them in a list (you clearly already know how lists work) and choose the appropriate one.
Also, don't use indices just because you want to modify each element of the list. You can just create a new list and reassign it in place. Or better yet, use a list comprehension to describe how the old list is transformed into the new one.
class MyClass(object):
def __init__(self, input1, input2):
self.attributes = [
[(a1_d1, a1_p1), (a1_d2, a1_p2)],
[(a2_d1, a2_p1), (a2_d2, a2_p2), ..., (a2_d10, a2_p10)],
# etc.
]
def update_probabilities(self, which_attribute, decision):
self.attributes[which_attribute] = [
(action, new_probability_for(action, current_probability, decision))
for (action, current_probability) in self.attributes[which_attribute]
]
精彩评论