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'
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With