0

If I have an image class:

class Image:
    def __init__(self, image):
        self.image = image

How can I pass an instance of Image to a function and have it converted to a data type automatically?

For instance, if I want to show the image:

img = Image(some_image)
plt.imshow(img)

I don't want to have to go:

plt.imshow(img.image)

The same way that you don't have to specify that you want the values from a numpy array when you pass it into functions.

trent
  • 25,033
  • 7
  • 51
  • 90
Dwarf
  • 44
  • 1
  • 6
  • 3
    You have to make sure your image class is [array_like](https://stackoverflow.com/questions/40378427/numpy-formal-definition-of-array-like-objects). – user8153 Sep 29 '17 at 04:35
  • Depending on how complicated the `image` class is, are you sure you even need a separate class? It may be simpler to just have arrays and a few additional functions if there is only one attribute. – Edward Minnix Sep 29 '17 at 04:49
  • I found your code confusing because the names were not consistent. I have made some edits to make the names more meaningfully distinct. Please check that my edits have not accidentally introduced an error. – trent Sep 29 '17 at 22:11

1 Answers1

1

Try this:

class image:
   def __init__(self, image):
         self.img = image

   def __repr__(self):
         return repr([self.img])

Hope this helps!

---By Request---

Ok I will try my best to explain how this code works. If you have ever printed a class object - then you will probably get an output that looks something like this

<__main__.ExampleClass object at 0x02965770>

The __init__ function is a constructor method. In python there are several constructor methods which all have a prefix of __ and a suffix of __. These tell the interpreter how to handle to the object. For example there is a constructor method: __del__ which tells python what to do when you call del() on the object. Like this __repr__ is an constructor method too. 'repr' is short for represent - what python should represent the object - it's default value. Normally you would return a value without the repr() function. Repr() is a magic method (like del()) and what it does is it calls the __repr__ method of the object inside of the brackets. It must be known that each data type - variable, list, tuple, dictionary etc. Are actually instances of a class. Each data type has it's own __repr__ method - telling python how it should represent it, because remember on the computer everything is in binary. This means when you return the representation of the image, you don't return it as a string, but as an object.

I'm not the best at explaining, but hopefully this clears some things up. If anyone has a better way of explaining this go ahead.

Ben10
  • 500
  • 1
  • 3
  • 14