0

I'm trying to create a custom class for dimensionality that I can basically use as an integer but also add metadata and units to in the process.

I am trying to follow the class inheritance tutorial: https://www.python-course.eu/python3_inheritance.php but it doesn't like my extra attributes.

How can I create this class?

I want to be able to do the following:

m = Dimension(4, "iris_feature")
m + 1 # 5
np.random.normal(size=(150,m))
m.metadata["notes"] = "Darth Plagueis still lives"
print(f"This dimension's units are {m.unit}s") # This dimension's units are iris_features

Here is my attempt to make the class:

class Dimension(int):
    def __init__(self, size, unit=None, metadata=None):
        self.size = size
        self.unit = unit
        self.metadata = dict() if metadata is None else metadata
    def __repr__(self):
        return f"Dimension(size: {self.size}, unit: {self.unit})"

n = Dimension(150, "iris_sample")
m = Dimension(4, "iris_feature")

Here is my error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-e0983ebb366a> in <module>()
      7         return f"Dimension(size: {self.size}, unit: {self.unit})"
      8 
----> 9 n = Dimension(150, "iris_sample")

TypeError: 'str' object cannot be interpreted as an integer
O.rka
  • 29,847
  • 68
  • 194
  • 309
  • 1
    `int` objects are immutable, so define `__new__`, not `__init__`. – Martijn Pieters Apr 26 '18 at 20:30
  • Do you have any recommendations on what is going wrong here: class Dimension(int): def __new__(size, unit=None, metadata=None): return super(Dimension, size).__new__(size, unit, metadata) – O.rka Apr 26 '18 at 20:38
  • 1
    `int()` doesn't take a unit or metadata, so don't pass those in. Set those as attributes on the return value of `super().__new__(cls, size)`. – Martijn Pieters Apr 26 '18 at 20:40
  • Thanks, I thought `cls` was a custom attribute the other person was defining. – O.rka Apr 26 '18 at 21:02
  • @MartijnPieters I'm still having trouble getting it to work. Do you have any suggestions? The answer's in the referenced duplicates are not directly applying to this case. – O.rka Apr 26 '18 at 21:28
  • 1
    Here's a working example: https://gist.github.com/mjpieters/3a011c2bf4da43e28bc22823eeff0b0a – Martijn Pieters Apr 26 '18 at 21:46

0 Answers0