Dwarf
Dwarf

Reputation: 44

How do I set up a default type for a python class?

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.

Upvotes: 0

Views: 181

Answers (1)

Ben10
Ben10

Reputation: 498

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.

Upvotes: 1

Related Questions