I'm trying to make a set of functions that will implement a caesar cipher by defining new classes, within which is the actual code for the cipher. trying to run it gives me an attribute error:
original = self.get_message_text()
AttributeError: 'str' object has no attribute 'get_message_text'
Full code is posted below.
import string
class Message(object):
def __init__(self, text):
self.message_text = text
#self.valid_words = load_words(WORDLIST_FILENAME) - commented out bc irrelevant here
def get_message_text(self):
'''
Used to safely access self.message_text outside of the class
Returns: self.message_text
'''
return self.message_text
def build_shift_dict(self, shift):
letters_lower, letters_upper = string.ascii_lowercase, string.ascii_uppercase
new_dict={}
for letter in letters_upper:
new_dict[letter] = letters_upper[(letters_upper.index(letter) shift) % 26]
for letter in letters_lower:
new_dict[letter] = letters_lower[(letters_lower.index(letter) shift) % 26]
return new_dict
def apply_shift(self, shift):
original = self.get_message_text()
new = ''
for letter in original:
new = (self.build_shift_dict(shift))
#print(new) - a test print
return new
print(Message.apply_shift('tweLve',12))
disclaimer: this is a part of the MIT edx python course but I've checked through all of their notes & forum posts and I am none the wiser. Any help would be appreciated
EDIT: full error message, also I forgot to add the final print statement in the code
Traceback (most recent call last):
File ~.spyder-py3\ps5.py:239 in print(Message.apply_shift('tweLve',12))
File ~.spyder-py3\ps5.py:129 in apply_shift original = self.get_message_text()
AttributeError: 'str' object has no attribute 'get_message_text'
CodePudding user response:
You have to initiate the class object before running its functions
Full code:
import string
class Message(object):
def __init__(self, text):
self.message_text = text
# self.valid_words = load_words(WORDLIST_FILENAME) - commented out bc irrelevant here
def get_message_text(self):
'''
Used to safely access self.message_text outside of the class
Returns: self.message_text
'''
return self.message_text
def build_shift_dict(self, shift):
letters_lower, letters_upper = string.ascii_lowercase, string.ascii_uppercase
new_dict = {}
for letter in letters_upper:
new_dict[letter] = letters_upper[(letters_upper.index(letter) shift) % 26]
for letter in letters_lower:
new_dict[letter] = letters_lower[(letters_lower.index(letter) shift) % 26]
return new_dict
def apply_shift(self, shift):
original = self.get_message_text()
new = ''
for letter in original:
new = (self.build_shift_dict(shift))
# print(new) - a test print
return new
if __name__ == '__init__':
class_obj = Message(text='foo')
original = class_obj.get_message_text()
print(original)
CodePudding user response:
You should create instance of class and use this instance with apply_shift()
item = Message("tweLve")
print( item.apply_shift(12) )