创建多个对象后如何访问特定的对象属性?蟒

时间:2015-07-21 23:30:29

标签: python oop

我正在尝试通过创建管理电影商店的OO代码来练习Python编码。我所做的代码工作正常,做我想要的,但在我的代码中,对象Movie有2个属性(名称,ncopies),我使用列表关联每个电影名称有了自己的 ncopies 属性,我想通过使用像 something.name 这样的Objected Oriented编程来访问这些属性,这给了我电影的名称,而不是必须维护2个相关列表,每次想要获取属性时都必须获取索引,有什么想法吗?

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() 

1 个答案:

答案 0 :(得分: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一样访问并查找dict以查找映射到份数的电影名称