我試圖通過創建名稱從列表中獲取名稱而不是創建對象和重複傳遞實例的對象來實現此重複塊代碼。python通過引用對象名稱通過變量創建對象,從列表中創建對象
class waittill:
def __init__(self,path):
self.imagepath = os.path.join("C:\python\python_projects\pyautogui\images", path)
loaded=waittill("loaded.png")
agree=waittill("agree.png")
firstname=waittill("firstname.png") #This works absolutely fine
loginid=waittill("loginid.png") #I wish repetition could be avoided
password=waittill("password.png")
loginbutton=waittill("loginbutton.png")
customerlist=waittill("customerlist.png")
loginpage=waittill("loginpage.png")
customerinfo=waittill("customerinfo.png")
profile=waittill("profile.png")
是有可能寫出一個更優雅的代碼,例如通過列表循環創建對象
images=["loaded.png","agree.png","firstname.png","loginid.png","password.png","loginbutton.png","logout.png","middlename.png","lastname.png","submit.png",\
"customerlist.png","loginpage.png","customerinfo.png","profile.png"]
for each_image in images:
a,b=each_image.split(".")
b=(a+"."+b)
image=b.strip()
name=a.strip()
name=waittill(image) #this is where the problem lies, its repeatedly naming the object *name* and not say *loaded* or *agree*.
我不知道你的問題是什麼。你寫的代碼有什麼問題? –
使用字典 – BlackBear
類「waittill」的名稱「a」的對象正在創建,而不是創建對象,我隱式引用了一個ie a = loaded @DanielRoseman –