[英]Is there a way to access specific attributes in a list of objects in python?
[英]How to access specific object attributes after creating multiple objects? Python
我正在嘗試通過創建管理電影商店的OO代碼來練習Python編碼。 我完成的代碼可以正常工作,並且可以完成我想要的事情,但是在我的代碼中對象Movie具有2個屬性(名稱,ncopies),我正在使用一個列表將每個電影名稱與自己的ncopies屬性相關聯,想要通過使用諸如something.name之類的面向對象編程來訪問這些屬性,這給了我電影的名字,而不是必須維護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()
您可以改用dict object()將影片名稱映射到ncopies。 就像是
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
這樣M.m_dict
並在dict中查找映射到副本數的電影的名稱
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.