Creating class instance based on user input - python

Suppose I had this class
class employee(object)
def __init__(self,name):
return self.name
def something(self):
pass
...
Leading to
if __name__== "__main__":
name = input("what is your name ")
user1 = employee(name)
user1.something()
...
I want the user1 instance to be the name inputted by the user so that I can have unique instances. How do I go about adding instances based on user input in the main section?
so if I run the program and inputted "tim", the outcome I would want is:
tim.name = "tim"
....
UPDATE
Seems like the above is unclear, let me try to explain using my actual code:
So I have this Spotify API:
class Spotify(object):
def __init__(self,user):
self.client_id = ''
self.client_secret = ''
def client_credentials(self):
pass
def get_header_token(self):
pass
...
In the end,
if __name__== "__main__":
user = input("Enter username ")
user = Spotify(user)
user.request_author()
...
I am trying to get the user variable to the input the user provides, such as if the user inputted "tim123", the user variable would also be tim123.
So I could perform:
tim123.name
Think my mind is going completely blank and there should be an easy solution for this. I am sure this is very unpractical but I don't know how I would do this in case I ever needed to.

Change
return self.name
to
self.name = name
if name== "main":
variable_name = raw_input("Enter variable name:") # User.
enters "tim123"
name = input("Enter Name")
globals()[variable_name] = employee(name)
tim123.name

Based on your comment, it sounds like you are looking for exec() or eval(). Link. My solution would be to do something like:
class employee(object):
def __init__(self,name):
self.name = name
name = input("what is your name ")
exec(f"{name} = employee('{name}')")
(and then you would access joe.name, if the user inputted joe, or bob.name, if the user inputted bob, etc.).
Alternatively, you could use locals() or globals()
Hope this helped!

Related

taking input from user to decide which object will be used in python class

i am new here and i am trying to learn python. i want to create a simple atm program but i also want to try something that i haven't seen yet. i want to take input from user and select one of objects of a class regard to this selection, here is the part of my code
class bankaccount():
def __init__(self,name,money):
self.name=name
self.money=money
def show(self):
print(self.name,self.money)
johnaccount=bankaccount("john",500)
mikeaccount=bankaccount("mike",1000)
sarahaccount=bankaccount("sarah",1500)
selection= input("please write the name: ")
for example i will write john and program should run johnaccount.show is this possible? could you please help about this issue.
Below
class bankaccount():
def __init__(self,name,money):
self.name=name
self.money=money
def show(self):
print(self.name,self.money)
# build the accounts 'DB' (which is just a dict)
# read more here: https://cmdlinetips.com/2018/01/5-examples-using-dict-comprehension/
accounts = {name: bankaccount(name,balance) for name,balance in [("john",500),("mike",1000)]}
user = input("please write the name: ")
account = accounts.get(user)
if account:
account.show()
else:
print(f'no account for {user}')
There is a "hacky" way to do that (see below). Usually you'd rather have a dictionary or list containing all of the accounts and then get the account from there.
For example:
accounts = {
'john': bankaccount("john",500),
'mike': bankaccount("mike",1000)
}
selection = input("please write the name: ")
if selection in accounts:
print(f"Balance: {accounts[selection].show()}")
else:
print("Account not found")
The "hacky" way is to use Python's built-in locals function:
johnaccount=bankaccount("john",500)
mikeaccount=bankaccount("mike",1000)
sarahaccount=bankaccount("sarah",1500)
selection = input("please write the name: ")
account_name = f"{selection}account"
if account_name in locals():
print(f"Balance: {locals()[account_name].show()}")
else:
print("Account not found")
The f"Balance: {accounts[selection].show()}" syntax that I'm using is called f-strings, or formatted string literals.
PS. it's common practice to use CamelCase for class names, e.g. BankAccount, and to use lowercase and underscores for variable names, e.g. john_account.

NameError trying to use a custom class

I am new to Python, am just learning Classes, and am trying to write a "personal info" program:
This is my code:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
def addresses(self, add):
add = raw_input("What is your adress?")
self.addresses = add
def ages(self, age):
age = raw_input("What is your age?")
self.ages = age
def numbers(self, number):
number = raw_input("What is your phone number?")
self.numbers = number
PersonalInfo()
def print_names():
info = PersonalInfo()
print "Name:", info.names(name)
print "Address:", info.addresses(add)
print "Age:", info.info.ages(age)
print "Phone number:", info.numbers(number)
print_names()
But when I run it it says this:
NameError: global name 'add' is not defined
Can someone please help me?
There are several issues with your code other than the NameError and I strongly suggest you read more on python classes:
https://docs.python.org/2/tutorial/classes.html
https://www.tutorialspoint.com/python/python_classes_objects.htm
https://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Classes
I'll run you through those issues.
First, the NameError occurs because the add variable was not defined. The same applies to all other arguments you provided in your print statements.
Second, there are issues with the way you define the class methods:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
Here, you are re-assigning the name variable to the return value of raw_input so there's no sense in setting it as an argument in the first place. Also, by stating self.names = name you are re-assigning the class method to the string that is returned by raw_input!
Third, you have to decide whether you want to provide the information when calling the methods, or using raw_input. Here's a working example of your code, assuming you want to use raw_input
class PersonalInfo():
def names(self):
name = raw_input("What is your name?")
self.name = name
def addresses(self):
add = raw_input("What is your adress?")
self.address = add
def ages(self):
age = raw_input("What is your age?")
self.age = age
def numbers(self):
number = raw_input("What is your phone number?")
self.number = number
def print_names():
info = PersonalInfo()
# Get information
info.names()
info.addresses()
info.ages()
info.numbers()
# After getting the info, print it
print "Name:", info.name
print "Address:", info.address
print "Age:", info.age
print "Phone number:", info.number
print_names()

Beginner Python Classes - changing the attribute value with user input

I am just learning classes in Python and for the past day I am stuck with the below.
I am trying to use a user input (from the main() function) to change the value of an attribute in the class.
I have been throught the #property and #name.setter methods that allow you to change the value of a private attribute.
However I am trying to find out how you can use user input to change the value of an attribute that is not private.
I came up with the below but it does not seem to work. The value of the attribute remains the same after I run the program. Would you have any ideas why?
class Person(object):
def __init__(self, loud, choice = ""):
self.loud = loud
self.choice = choice
def userinput(self):
self.choice = input("Choose what you want: ")
return self.choice
def choiceimpl(self):
self.loud == self.choice
def main():
john = Person(loud = 100)
while True:
john.userinput()
john.choiceimpl()
print(john.choice)
print(john.loud)
main()
In choiceimpl you are using == where you should use =.
Like stated before, you are using a comparison with == instead of the =.
Also you are returning self.choice in userinput as a return value, but never use it, because you set self.choice equal to input.
Shorter example:
class Person:
def __init__(self, loud):
self.loud = loud
def set_loud(self):
self.loud = input("Choose what you want: ")
def main():
john = Person(100)
while True:
john.set_loud()
print(john.loud)
main()
1) Change: '=='(comparison operator) to '='(to assign)
2) Inside class:
def choiceimpl(self,userInp):
self.loud = self.userInp
3) Outside class
personA = Person(loud) # Create object
userInp = raw_input("Choose what you want: ") # Get user input
personA.choiceimpl(userInp) # Call object method

Using Input in User Defined Functions!(Python)

I am wondering, is there a way to use the input() function inside a user-defined function? I tried doing this
def nameEdit(name):
name = input()
name = name.capitalize
return name
Using input is fine. However, you aren't calling name.capitalize; you're just getting a reference to the method and assigning that to name. [Further, as pointed out by Bob, your function doesn't need a name argument.] The correct code would be
def nameEdit():
name = input()
name = name.capitalize()
return name
or more simply:
def nameEdit():
return input().capitalize()
Are you talking about asking for input from a user from a method? If so then this would be what you're looking for:
def nameEdit():
name = input("Enter your name: ")
name = name.capitalize()
return name

Python input Job Code

I'm Code doesn't seem to work, I am trying to get input of a job, category, and salary, and store the input
class Jobs:
def GetJob(self):
name = raw_input('Enter a Job Title: ')
category = raw_input('Enter what Category that Job is: ')
salary = raw_input('Enter the salary of that Job: ')
print name,category, salary
def __init__(self,name,category,salary):
self.name = Jobs.GetJob(name)
self.category = Jobs.GetJob(category)
self.salary = Jobs.GetJob(salary)
GetJob = Jobs()
print GetJob
Your code is totally out of good OOP practices, and the first part eandersson's answer too…
A class has for role to store values, get/set them and return (or apply) transformations to its encapsulated values. What you tried to achieve is totally nonsense: you're calling the GetJob method of the Jobs class inside another method. It could work if you would have written:
def __init__(self,name…):
self.name = Jobs.GetJob(self, name)
…
But that would be a wrong way to design your program. You'd better stick your class to hold your values and making it good at that, and make another function that helps populate your class:
class Jobs:
def __init__(self, name, category, salary):
self.name = name
self.category = category
self.salary = salary
def __repr__(self):
return "Jobs<%s,%s,%s>" % (self.name, self.category, self.salary)
def GetJob():
name = raw_input('Enter a Job Title: ')
category = raw_input('Enter what Category that Job is: ')
salary = raw_input('Enter the salary of that Job: ')
return Jobs(name, category, salary)
print GetJob()
I do not agree with eandersson's approach because it deceives the purpose of the constructor, by directly calling the GetJob method. Then GetJob is not useful. And one would want to be able to use the Job class without always having the raw inputs at construction. EDIT: valid only as a comment on the first part of his answer.
And finally, I think that you really misunderstands a lot about programming. You should better read thoroughly a python course like the ones on http://wiki.python.org/moin/BeginnersGuide/NonProgrammers, because there's really a lot of concepts you ignored to be able to write something like that.
go have a look at:
http://hetland.org/writing/instant-hacking.html
http://www.learnpython.org/
http://cscircles.cemc.uwaterloo.ca/
http://learnpythonthehardway.org/book/

Categories