0

I have written a custom Class that mimics physical units like meter, second, etc. Now I have implemented the classes in such a way that the user instantiates the class with a value, e.g.

class Unit(BaseUnit):
    def __init__(self, value, unitinformation):
        super(Unit, self).__init__(unitinformation)
        self.value = value

    def __mul__(self, other):
        value = self.value * other
        return self.__class__(value=value, self.unitinformation)

class Meter(Unit):
    def __init__(self, value):
        super(Meter, self).__init__(value, "stuff that defines Meter")

With BaseUnit being an abstract baseclass that takes care of possible conversions etc. This all works fine, but I would also like that it it possible for example to write

myUnit = 5 * Meter

which should be equivalent to

myUnit = Meter(5)

Is there any way, that the magic methods both accept classes and instances (possibly without using a metaclass)?

Torilla
  • 383
  • 5
  • 16
  • I guess the closes you will get is `Meter.one = Meter(1)` and then use 'Meter.one` – Patrick Artner Feb 22 '19 at 12:27
  • [Here](https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types)'s a list of dundermethods for numeric operations that you may want to implement. – Aran-Fey Feb 22 '19 at 12:30

0 Answers0