amirreza870
amirreza870

Reputation: 33

Python OOP - Change class text

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.

Upvotes: 1

Views: 31

Answers (1)

STerliakov
STerliakov

Reputation: 7963

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

Upvotes: 2

Related Questions