私はオブジェクト指向設計の初心者です。Pythonクラスの初期化
私はにPython関数を組み込もうとしています。 (機能は、I asked earlierとして動作します)。
はここに私のコードです:
import struct
import urllib2
import StringIO
class wallpaper:
def __init__(self, url):
self.url = url
self.content_type = ''
self.height = 0
self.width = 0
image = urllib2.urlopen(self.url)
data = str(image.read(2))
if data.startswith('\377\330'):
self.content_type = 'image/jpeg'
jpeg = StringIO.StringIO(data)
jpeg.read(2)
b = jpeg.read(1)
try:
while (b and ord(b) != 0xDA):
while (ord(b) != 0xFF): b = jpeg.read(1)
while (ord(b) == 0xFF): b = jpeg.read(1)
if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
jpeg.read(3)
h, w = struct.unpack(">HH", jpeg.read(4))
break
else:
jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
b = jpeg.read(1)
self.width = int(w)
self.height = int(h)
except struct.error:
pass
except ValueError:
pass
x = wallpaper('http://i.imgur.com/rapwX.jpg')
print x.url, "\t", x.content_type,"\t", x.height,"\t", x.width
問題は、私は高さと幅のプロパティを初期化することができないということである(彼らは0等しいです)。
問題はどこですか?
編集:
私が見つけた問題は、ここにsolutionです。あなたのヒントをありがとう。
もう1つ質問:OOPルールに関する限り、私のアプローチは適切ですか? で幅/高さを計算するか、他の方法(サイズなど)を作成する必要がありますか?
バイナリデータを使って自分で演奏するのではなく、(Python Image Library)[http://www.pythonware.com/products/pil/]を使ってすべての低レベルのものを扱うことができます。 – katrielalex
なぜValueErrorは無視されますか? (とstrtuct.error?) – rvs