1

I want to create class instances and name them with user input strings. Something like this, that actually works. Any ideas?

class Account:
     balance=0

input("What's your name?") = Account()

If the user were to type Scott, I would like to be able to call attributes using Scott.balance etc.

5 Answers 5

1

You are probably better off storing them in a dictionary. Creating variables in the global / local space with user input is a recipe for trouble.

accounts = {}
account[x] = Account()
Sign up to request clarification or add additional context in comments.

2 Comments

So this would create an instance in an array, which is nice. But How would I incorporate a user's name to name the array, which would allow me to call it's properties with the syntax i.e. Jack.balance?
account[name].balance += 100
1

Use built-in raw_input to have user input as argument of your 'constructor'

class Account:
     def __init__(self, name=0, money=0):
         self.name = name
         self.money = money

input = raw_input("What's your name? -->")
account = Account(input,10000)

Comments

0

Give your class an __init__ method:

class Account:
     def __init__(self, x=1, y=2):
         self.x = x
         self.y = y

And just initialize it:

def createAccount(x):
    return Account(x)

Comments

0

We can input string from outside the class by just passing it in to init as normal using two ways : input() or raw_input().

class Account:
     def __init__(self, balance):
        self.balance = balance
     def output_all(self):
        print( '{}'.format(self.balance))

MyAccount = Account(input('Type your account : '))

Account.output_all(MyAccount)

2 Comments

It will be great if you will explain your approach with the added code.
We can input string from outside the class by just passing it in to init as normal using two ways : input() or raw_input(). I hope that i well explained !
0

You can also add the input to a list, then create an instance of the class by referencing the list element:

class Account:
     balance=0

account_names = []

account_names.append(input("What's your name?"))

account_names[0] = Account()

To change/access class attribute, reference the list element:

>>> account_names[0].balance += 100
>>> account_names[0].balance
100

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.