1
我想創建4個類Tire實例,並將列表中的實例保存在列表中(All_Tires)並通過每個實例迭代(使用for循環)並打印成員每個實例。將類實例保存在python列表中並迭代每個實例
class Tire():
__identifier=0
__temperature=0
__pressure=0
__pressure_position=0
__temperature_position=0
__pressure_font=0
__temperature_font=0
__background_area =0
__color=0
def __init__(self,fourbyteid,backarea,presspos,temppos,press=0,temp=0,bkcolor=GREEN):
self.__identifier=fourbyteid
self.__temperature=temp
self.__pressure=press
self.__pressure_position=presspos
self.__temperature_position=temppos
self.__background_area=backarea
self.__color=bkcolor
from tire import Tire
class ScreenArea(object):
def __init__(self,x,y):
self.w=x
self.h=y
# Set the width and height of the screen [width, height]
ssize = ScreenArea(320,240)
FL = Tire("0d224bff",
(0,0,ssize.w/2,ssize.h/2),
(ssize.w*1/8, ssize.h/4),
(ssize.w*1/8, ssize.h/4))
FR = Tire("0d224bf4",
(ssize.w/2,0,ssize.w/2,ssize.h/2),
(ssize.w*3/4, ssize.h/4),
(ssize.w*3/4, ssize.h/4))
RL = Tire("0d2262b9",
(0,ssize.h/2,ssize.w/2,ssize.h/2),
(ssize.w*1/8, ssize.h*3/4),
(ssize.w*1/8, ssize.h*3/4))
RR = Tire("0d22622a",
(ssize.w/2,ssize.h/2,ssize.w/2,ssize.h/2),
(ssize.w*3/4, ssize.h*3/4),
(ssize.w*3/4, ssize.h*3/4))
All_Tires=[FL,FR,RL,RR]
print All_Tires
for tire in All_Tires:
print tire.__pressure
我希望print語句輸出一個 「0」,而不是收到錯誤消息「AttributeError的:輪胎實例沒有屬性 '__pressure'
如果無法確定是什麼你正在做或應該做什麼,不要弄亂名字。 – timgeb
有關此行爲的詳細信息:https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references –