Hi everyone! I’m doing the “Python for Data Science: Intermediate” course now and I’ve been struggling to understand the concept of classes (Object-Oriented Python) for two days. So I thought of a fun project to practice it!
I created a class, called CoolText! The purpose of this class is to create cool (or maybe not so cool?) texts from regular (boring) texts.
CoolText has two attributes:
- text: a string capitalized
CoolText has two methods:
- coolify(): takes self as a parameter and returns a cool text
- uncoolify(): takes a parameter: key (possible values: upper, lower, capitalize (default) and returns the original text in the desired form. (I added this parameter to practice using multiple parameters)
Thinking about what attributes and methods my class could have and implementing them helped me finally understand how classes work (or at least I hope so)
If you have time, please feel free to provide any feedback, suggestions for improvement! Thank you!
example_text = "This is an example text! Isn't it cool?" example_key = "lower" another_ex_key = "upper" third_ex_key = "capitalize" fourth_ex_key = "no key" uncool_chars = ["A", "L", "M", "O", "T", "I", "E", "S", "X"] cool_chars = ["@", "し", "Ⓜ", "Ø", "ィ", "！", "℮", "＄", "メ"] class CoolText: def __init__(self, text): self.text = text.upper() # capitalizes the original text def coolify(self): """ Return a cooler modified version of the original text """ cool_text = "" for i, e in enumerate(self.text): # loops through the index and character of the original text if e in uncool_chars: # if the character is in uncool_chars: ind = uncool_chars.index(e) # gets the index of the character in uncool_chars list e = cool_chars[ind] # replaces the character with the charecter in cool_chars list cool_text += e # adds the character to the new cool_text string else: cool_text += e # if not in uncool_chars, adds the char itself to cool_text return cool_text # returns the new cool_text def uncoolify(self, key="capitalize"): # works the same way as coolify() """ Return (almost) the original boring text """ uncoolified_text = "" for i, e in enumerate(self.text): if e in cool_chars: ind = cool_chars.index(e) e = uncool_chars[ind] uncoolified_text += e else: uncoolified_text += e # use capitalize(), upper() or lower() for if key == "lower": uncoolified_text = uncoolified_text.lower() elif key == "upper": uncoolified_text = uncoolified_text.upper() else: uncoolified_text = uncoolified_text.capitalize() return uncoolified_text mytext = CoolText(example_text) my_cool_text = mytext.coolify() print(my_cool_text) my_new_boring_text = CoolText(my_cool_text) print(my_new_boring_text.uncoolify(example_key)) print(my_new_boring_text.uncoolify(another_ex_key)) print(my_new_boring_text.uncoolify(third_ex_key)) print(my_new_boring_text.uncoolify(fourth_ex_key))