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()
您会考虑使用一个字典对象的数量的电影叫什么名字? – Sentient07
嗨,谢谢你的回答,我认为这样可以很好地工作,但是如果我想在电影类中添加更多属性(名称,年份,ncopies,流派等),那么你解决了我的问题,但那不是什么我试图做=) –
你可以使用像{名称:{<另一个字典映射数据}} – Sentient07