Python: программа для банкоматов - PullRequest
0 голосов
/ 05 августа 2020

В моей программе Python я создал один класс userdetails - (хотя у меня есть несколько других классов, которые я хочу добавить позже). Я создал 2 объекта из этого класса, но не могу назвать их все? это моя проблема. Я хочу связать отдельные pin_no с отдельными объектами и вызывать их по отдельности с их данными.


from Details import userdetails


pin_no = (1111, 2222)

while True:

    pin_no = input("Input the no : ")

    if pin_no == '1111' or pin_no == '2222':
        
        
        print ("\n Hello and welcome to my program.  Please choose from one of the following options:")
        
        break
    
    else:
    
        print ("please try again ")
            
            
            
newuserdetails = userdetails ('Tom', '23 Bishop St ', 'cv3_f45', 2347477472)

newuserdetails1 = userdetails ('Bill', '81 Oliver St ', 'CV6 7FR', 574747477)   
  
  
user =  input("\n\n 1. Userdetails \n 2. Address \n 3. Post Code \n 4. Tel No " '\n')

a = '1'
b = '2'
c = '3'
d = '4'


if user == a:

    print (newuserdetails.name) or (newuserdetails1.name) 
    
elif user == b:
    
    print (newuserdetails.address)
     
elif user == c:
    
    print (newuserdetails.post_code)
    
elif user == d:
    
    print (newuserdetails.tel_no)

1 Ответ

0 голосов
/ 05 августа 2020

Я считаю, что то, что ищете, - это словарь.

newuserdetails = userdetails ('Tom', '23 Bishop St ', 'cv3_f45', 2347477472)
newuserdetails1 = userdetails ('Bill', '81 Oliver St ', 'CV6 7FR', 574747477)
newuserdetails2 = userdetails ('John', '35 Main St ', 'CRF 250R', 435247477)


# create the dictionary right after you create the class, so they can be in the same scope
# whenever you would reference newuserdetails, you can now reference the dictionary object

dict = { # if you know all the users when you create the dictionary
  '1111': newuserdetails,
  '2222': newuserdetails1,
}

# to add a user after the dictionary has been created
dict['3333'] = newuserdetails2

Затем вы можете получить экземпляр сведений о пользователе с помощью пина, используя это:

dict['1111'] # returns newuserdetails

# instead of using:
newuserdetails.name # returns 'Tom'

# you can now use:
dict['1111'].name # returns 'Tom'

# Or you could assign it to a temp variable if that makes more sense
currentuserdetails = dict['1111']
currentuserdetails.name # still returns 'Tom'

Я предостерегаю от использования пин-код, тем не менее, как способ получить пользователя.

Если два пользователя случайно выберут один и тот же пин-код, возникнут ошибки, и ваш код сломается. Вам лучше использовать идентификаторы для получения сведений о пользователе

Изменить:

Вот что я использую, и он работает должным образом на python 3,8

class userdetails:
    def __init__(self, name, addr, num, number):
        self.name = name
        self.address = addr
        self.post_code = num
        self.tel_no = number


pin_no = (1111, 2222)

while True:
    pin_no = input("Input the no : ")
    if pin_no == '1111' or pin_no == '2222':
        print ("\n Hello and welcome to my program.  Please choose from one of the following options:")     
        break
    
    else:
        print ("please try again ")
            
               
newuserdetails = userdetails ('Tom', '23 Bishop St ', 'cv3_f45', 2347477472)
newuserdetails1 = userdetails ('Bill', '81 Oliver St ', 'CV6 7FR', 574747477)   
dict = {
  '1111': newuserdetails,
  '2222': newuserdetails1
}

user =  input("\n\n 1. Userdetails \n 2. Address \n 3. Post Code \n 4. Tel No " '\n')

a = '1'
b = '2'
c = '3'
d = '4'


if user == a:
    print (dict[pin_no].name)
elif user == b:
    print (dict[pin_no].address)
elif user == c:
    print (dict[pin_no].post_code)
elif user == d:
    print (dict[pin_no].tel_no)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...