2016-11-21 37 views
-2

我越來越喜歡的問題:使用__str__方法返回的矩形座標

SyntaxError 
invalid syntax (prog1.py, line 114) 

我得到這樣的錯誤,當我嘗試使用STR方法返回座標,lenght,widht和顏色一個我已經編碼過的矩形。

def __str__ (self): 
    return ("starting point:""("self.x,self.y")""\n""width:"self.w"\n""lenght:"self.h"\n""color("self.r,self.g,self.b")") 

在哪裏我應該得到

'starting point:(100,20)\nwidht:400\nlenght:120\ncolor(100,255,0)' 

回答

2

串聯串(以及其他類型)的一樣,在Python

不起作用

你能做到starting_point:("+str(self.x)+","+str(self.y) ...但會很麻煩。

你需要str.format,與{}佔位符和作爲format方法的參數數據,像這樣:

return ("starting point:({},{})\nwidth:{}\nlength:{}\ncolor({},{},{})".format(self.x,self.y,self.w,self.h,self.r,self.g,self.b))