2017-09-29 33 views
0

如果我有一個形象類:如何爲python類設置默認類型?

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

如何傳遞的Image一個實例函數,並將它轉換爲自動數據類型?

舉例來說,如果我想顯示圖像:

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

我不希望有去:

plt.imshow(img.image) 

,你不必指定用同樣的方法當你將它傳遞給函數時,你需要一個numpy數組的值。

+3

你必須確保你的圖像類是[array_like](https://stackoverflow.com/questions/40378427/numpy-formal-definition-of-array-like-objects)。 – user8153

+0

根據'image'類的複雜程度,你確定你甚至需要一個單獨的類嗎?如果只有一個屬性,只需要有數組和一些附加功能可能會更簡單。 –

+0

我發現你的代碼令人困惑,因爲名稱不一致。我做了一些編輯,使名稱更加有意義的不同。請檢查我的編輯是否沒有意外引入錯誤。 – trentcl

回答

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.

我不是最好的是解釋,但希望這會清除一些東西了。如果任何人有更好的方式解釋這一點,請繼續。

+0

謝謝,但那不是我要找的。我希望它在數組被調用時轉換爲數組。不是字符串 –

+0

再次嘗試代碼 - 希望它能正常工作 – Ben10

+0

您還可以解釋您在做什麼,而不是僅僅提供解決方案嗎? – Chiel

相關問題