Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python class to print bash colors

I have python scripts that will print to screen, and sometimes I want them bold, or green, and sometimes both bold and green. But I can't seem to figure out how to do both.

class colortext():
    def __init__(self, text:str):
        self.text = text
        self.ending = '\033[0m'

    def bold(self):
        return '\033[1m' + self.text + self.ending

    def green(self):
        return '\033[92m' + self.text + self.ending


print(colortext('hello').bold().green())

AttributeError: 'str' object has no attribute 'green'
like image 460
BML Avatar asked Feb 10 '26 22:02

BML


1 Answers

Because you're returning a string in the bold and green methods. I think you actually want to return a reference to the colortext object itself. So modify the text in those methods and return self. Also if you want it to print the string when you call it in print, define the __str__ function. Try:

class colortext():
    def __init__(self, text:str):
        self.text = text
        self.ending = '\033[0m'

    def __str__(self):
        return self.text

    def bold(self):
        self.text = '\033[1m' + self.text + self.ending
        return self

    def green(self):
        self.text = '\033[92m' + self.text + self.ending
        return self

print(colortext('hello').bold().green())
like image 83
doggie_breath Avatar answered Feb 12 '26 13:02

doggie_breath