2015-07-21 61 views
1

我試圖通過創建一個管理電影商店的OO代碼來練習Python編碼。我所做的代碼工作正常,做我想做的事,但在我的代碼中,對象電影有2個屬性(名稱,ncopies),我用列表關聯每個電影名稱與它自己的ncopies屬性,我想通過使用面向對象的編程,如something.name來訪問這些屬性,這給我的電影的名稱,而不是必須維護2相關列表,並必須獲得索引,每次我想要得到一個屬性,任何想法?如何在創建多個對象後訪問特定的對象屬性? Python

class Movie: 
    global lista_names 
    global lista_ncopies 
    lista_names = [] #list of movie names 
    lista_ncopies = [] #list of movie copies 

    def __init__(self, name, ncopies):#keeps movie name and ncopies with same index 
     self.name = name 
     self.ncopies = ncopies 
     lista_names.append(self.name) #append movie name to the list 
     lista_ncopies.append(self.ncopies) #append ncopies to the list 

def showNumberOfCopies(): 
    pesquisa = input("digite o nome")#variable receives the movie name 
    if pesquisa in lista_names: #checks if its in the movie names list 
     indice = lista_names.index(pesquisa) #gets its index 
     print ("num de copias de",pesquisa,"eh ",lista_ncopies[indice])   
    menu() 
def addMovie(): 
    name = input("digite o titulo") #get name of the movie 
    ncopies = int(input("digite o numero de copias"))#get num of copies 
    movie1 = Movie(name, ncopies) #create object 
    menu() 

def updateMovie(): 
    pesquisa = input("type the name of the movie ") 
    if pesquisa in lista_names: #checks if movie is in lista_names 
     indice = lista_names.index(pesquisa) #gets the index 
    else: 
     opcao = input("o filme desejado nao esta em nosso acervo, deseja atualizar outro filme? s/n") #just in case the movie is not in lista_names 
     if opcao == 's' or opcao == 'S': 
      updateMovie() 
     else: 
      menu() 
    opcao2 = input("update ncopies or movie name? type ncopias/nome") 
    if opcao2 == 'ncopias': 
     print ("the number of copies is: ",lista_ncopies[indice]) 
     ncopies_new = int(input("digite o numero de copias novo")) 
     lista_ncopies[indice] = ncopies_new 
     menu() 
    elif opcao2 == 'nome': 
     print ("name of the movie is",lista_names[indice]) 
     name_new = input("type the new name") 
     lista_names[indice] = name_new 
     print (lista_names) 
     menu()    

def menu(): 
    opcao = int(input('1-add filme\n2-search filme\n3-update\n4-exit')) 
    if opcao == 1: 
     addMovie() 
    elif opcao == 2: 
     showNumberOfCopies() 
    elif opcao == 3: 
     updateMovie() 
    elif opcao == 4: 
     quit  
    else: 
     menu()   


menu() 
+0

您會考慮使用一個字典對象的數量的電影叫什麼名字? – Sentient07

+0

嗨,謝謝你的回答,我認爲這樣可以很好地工作,但是如果我想在電影類中添加更多屬性(名稱,年份,ncopies,流派等),那麼你解決了我的問題,但那不是什麼我試圖做=) –

+0

你可以使用像{名稱:{<另一個字典映射數據}} – Sentient07

回答

0

您可以改爲使用將電影名稱映射到ncopies的dict對象()。像

class Movie: 
    global m_dict 
    m_dict = {} #dict object 

    def __init__(self, name, ncopies):#keeps movie name and ncopies with same index 
     self.m_dict = m_dict 
     m_dict[name] = ncopies #The other way if you wish 

然後有些事情,你可以訪問像M.m_dict查查字典映射到副本