How to organize a class, generate methods in it?

class Color:
 def __init__(self):
 self.Red = '\033[91m'
 self.Green = '\033[92m'
 self.Blue = '\033[94m'
 self.Cyan = '\033[96m'
 self.White = '\033[97m'
 self.Yellow = '\033[93m'
 self.Magenta = '\033[95m'
 self.Grey = '\033[90m'
 self.Black = '\033[90m'
 self.Default = '\033[99m'
 self.End_color = '\033[0m'

 def print_green(self, data):
 print(self.Green + data + self.End_color)

 def print_default(self, data):
 print(self.The Default + data + self.End_color)

color = color()
color.print_green("Some green text")
color.print_default("What deviltry text")


Possible as that to make so that not to write a method for each color?

you need to make an abstract method and override it apparently, but I can not understand implementation of this action.
June 14th 19 at 18:02
2 answers
June 14th 19 at 18:04
Solution
Might be better to make another argument when calling?

class Color:
 def __init__(self):
 self.red = '\033[91m'
 self.green = '\033[92m'
 self.blue = '\033[94m'
 self.cyan = '\033[96m'
 self.white = '\033[97m'
 self.yellow = '\033[93m'
 self.magenta = '\033[95m'
 self.grey = '\033[90m'
 self.black = '\033[90m'
 self.default = '\033[99m'
 self.end_color = '\033[0m'

 def color_print(self, data, color):
 print(getattr(self, color) + data + self.end_color)

obj = Color()
obj.color_print('Text in red', 'red')
obj.color_print('the green message', 'green')
obj.color_print('blue Text', 'blue')

The implementation is very clumsy, but as an option.

If you really need to generate class methods in real time, will have to get into meta-programming.

An example of solving a similar task: https://stackoverflow.com/questions/13194180/dynam...
June 14th 19 at 18:06
Solution
Easier and clearer to make an argument. But if hunting experiments, you can start with something like this:
def cprint(text):
 class colored():
 def __getattribute__(self, color):
 print(f text={text}, color={color}')
 return colored()

cprint('test').green

In General, it's the question of decorators, IMHO.

Find more questions by tags Python