Convert function into class Python

Asked by At

I'm having some issues regarding classes in Python because I'm in the need of refactoring some code.

The problem I'm facing is I have to refactor multiple similar scripts, so I decided to use Python classes but I have the following question

Say we have these two similar codes that need refactoring:

name = "Peter" 
print(f"Bye! {name}"}
name.replace("e", "a")
print(f"Bye! {name} **replaced**"}
name = "Lisa" 
print(f"Hi! {name}"}
name.replace("e", "a")
print(f"Hi! {name}"}

So a Python class:

class Greetings(object):
    def __init__(self):
        self.name = name

    def say_hi_and_replace(self, name):
        if name == "Lisa":
            print(f"Hi! {name}"}
        else:
            print(f"Hi! {name}"}
        self.name = self.name.replace("e", "a")


    def say_goodbye(self, name):
        if name == "Lisa":
            print(f"Bye! {name}"}
        else:
            print(f"Bye! {name} **replaced**"}

Is there a better way to write this code? I'm sure there is.

Edit: Besides using ternary operators like Klaud suggested correctly.

    def say_goodbye(self, name):
        print(f"Bye! {name}"} if name == "Lisa" else print(f"Bye! {name}"}

Edit: Sorry there was a typo in the "Bye!" Thanks in advance.

0 Answers