plutonium_gate
plutonium_gate

Reputation: 3

Is there a way to generate instances of a class

I'm trying to make sort of log in system but I'm not sure how to store data other than manually making lots of variables to store the names and passwords

class Acc:
   def __init__(self, name='', passw=''):
       self.name = name
       self.passw = passw

acc1 = Acc('ab','qw')
acc2 = Acc('kl', 'jm')
acc3 = Acc()
acc4 = Acc()
# ...
# etc

I want to make a function that creates an empty variable 'accx' then make it an instance of a class Acc() then have the user fill their name and password with the input function. accx = Acc(input('name: '),input('password: ') ) I'm sorry if the question is very stupid but I'm very new to coding so help would be greatly appreciated

Upvotes: 0

Views: 53

Answers (3)

jkr
jkr

Reputation: 19250

You can store the Acc instances in a list or dictionary. Then you don't have to make many variable names, and you can quickly reference any Acc instance.

I assume you aren't using this program for anything with sensitive data, but as best practice, you should enter passwords with the getpass.getpass function.

import getpass

class Acc:
    def __init__(self, name, passw):
        self.name = name
        self.passw = passw

# Hold all Acc instances in one list.
all_accs = []

def new_acc():
    name = input('name: ')
    passw = getpass.getpass('password: ')
    a = Acc(name=name, passw=passw)
    all_accs.append(a)

new_acc()  # enter name and password

# Now all_accs[0] references the `Acc` created in the line above.

The process would be similar if you want to store the Acc instances in a dictionary. You can map the user's name to their Acc instance.

# Hold all Acc instances in one list.
all_accs = {}

def new_acc():
    name = input('name: ')
    if name in all_accs:  # Check for existing name
        raise ValueError("name already exists")
    passw = getpass.getpass('password: ')
    a = Acc(name=name, passw=passw)
    all_accs[name] = a
    
new_acc()  # enter "John" and password

# Now all_accs["John"] references the `Acc` created in the line above.

Upvotes: 2

Bharel
Bharel

Reputation: 26901

How about using a dict (dictionary) to store your info?

Generally you'd like a database of some sorts, but sometimes a simple dict can help at the start:

import getpass

accounts = {}
while (name := input("Name: ")) != "!exit":
    passwd = getpass.getpass()  # Safer.
    accounts[name] = Acc(name, passwd)

Running it:

Name: Hey
Password:
Name: Hello
Password:
Name: !exit
>>> accounts
{'Hey': <__main__.Acc object at 0x000001BA01DF02E0>, 'Hello': <__main__.Acc object at 0x000001BA01F26850>}
>>> accounts["Hey"].passw
"I'm secret"

Upvotes: 0

Vivian
Vivian

Reputation: 345

You can change attributes after the instantiation. :)

accx = Acc()
accx.name = input('name:')
accx.passw= input('password:')

Upvotes: 0

Related Questions