Mickey Mahoney Mickey Mahoney - 1 month ago 19
Python Question

Where to change a value so it applies to all methods in python?

I am struggling with a problem that didn't seem to be a big deal in the beginning. I am creating aa class and a sub Subclass and whenever I want to change a value in subclass it should automatically update all the other methods in the class and subclass whenever I do that. Let me give you an example. The value that's supposed to be changed is

shift
in the
change.shift(shift)
method.

class Message(object):
'''
code that doesn't matter for this question
'''
def build_shift_dict(self, shift):
'''
code that doesn't matter for this question
'''
return dict

def apply_shift(self, shift):
'''
code that doesn't matter for this question
'''
return newMessage

class PlaintextMessage(Message):
def __init__(self, text, shift):
'''
code that doesn't matter for this question
'''
Message.__init__(self, text)
self.shift = shift
self.encrypting_dict = self.build_shift_dict(self.get_shift())
self.message_text_encrypted = self.apply_shift(self.get_shift())

def get_shift(self):
'''
Used to safely access self.shift outside of the class

Returns: self.shift
'''
return self.shift

def get_encrypting_dict(self):
return self.encrypting_dict

def get_message_text_encrypted(self):
return self.message_text_encrypted

def change_shift(self, shift):
assert 0 <= shift < 26
self.shift = shift


As you can see I need
shift
to be changed as well within
apply_shift(self, shift)
and
build_shift_dict(self, shift)
because the
init
method in
PlaintextMessage(Message)
calls does methods. How do I do that? When I call the
get_shift(self)
method I get the shift value, if I then call the
change_shift(self, shift)
method and call
get_shift(self)
again it shows me the updated
shift
value. So I tried to update
self.encrypting_dict = self.build_shift_dict(self.get_shift())
and
self.message_text_encrypted = self.apply_shift(self.get_shift())
with the get-Method instead of shift but that doesn't change anything. What am I missing here? Thanks!

Answer

In change_shift() just call those other two methods.

def change_shift(self, shift):
    assert 0 <= shift < 26
    self.shift = shift
    self.encrypting_dict = self.build_shift_dict(self.shift)
    self.message_text_encrypted = self.apply_shift(self.shift)

You could also define build_shift_dict and apply_shift without an argument, other than self, and just use self.shift in those methods - you would still have to call them but you wouldn't have to pass them anything, and you couldn't mess it up by passing those methods an erroneous value from your program.

Comments