Home > front end >  Python OOP - Change class text
Python OOP - Change class text

Time:06-07

Hi i wanna change the default text of a class. like __str__ or __repr__ for object

class Force(SIUnit):
    name = "Force"
    symbol = "F"
    unit = "N"


print(f"F = 1000{Force}")

something like this.

CodePudding user response:

You can define __str__ on metaclass:

class StringClassMeta(type):
    def __str__(cls):
        return cls.unit

class Force(metaclass=StringClassMeta):
    unit = 'N'

print(f'F = 1000 {Force}')
# F = 1000 N
  • Related