如何为python类设置默认类型?

时间:2017-09-29 04:29:45

标签: python class numpy

如果我有图像类:

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

如何将Image的实例传递给函数并将其自动转换为数据类型?

例如,如果我想显示图像:

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

我不想离开:

plt.imshow(img.image)

与将nty数组中的值传递给函数时不必指定所需的值相同。

1 个答案:

答案 0 :(得分:0)

试试这个:

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

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

希望这有帮助!

---按要求---

好的,我会尽力解释这段代码的工作原理。如果你曾经打印过一个类对象 - 那么你可能会得到一个看起来像这样的输出

<__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.

我不是最好的解释,但希望这能解决一些问题。如果有人有更好的解释方法,请继续。