Beginner Python Classes - changing the attribute value with user input - python

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

Related

How to make sure that no other instances have the same name from a class

class Satellite:
def __init__(self, message):
print(message)
self.name = input("name: ").title()
self.lbs = int(input("lbs: "))
self.speed = int(input("speed: "))
lstSat = []
e= input("Would you like to create satellites? If yes, type O. If not, type another letter: ").lower()
i=0
while e=="o":
lstSat.append(Satellite("Info for satellite "+str(i+1)))
i+=1
e= input("Type O to create another satellite: ").lower()
Hello,
How can I make sure that 2 Satellites cannot be the same?
Please don't ask for user input during class construction. Much better to acquire the values elsewhere then use a straightforward constructor based on the user's input values.
In order to determine repetition, you need to override the eq dunder method.
Try this:
class Satellite:
def __init__(self, name, lbs, speed):
self._name = name
self._lbs = lbs
self._speed = speed
def __eq__(self, other):
if isinstance(other, str):
return self._name == name
if isinstance(other, type(self)):
return self._name == other._name
return False
def __str__(self):
return f'Name={self._name}, lbs={self._lbs} speed={self._speed}'
lstSat = []
PROMPT = 'Would you like to create satellites? If yes, type O. If not, type another letter: '
while input(PROMPT) in 'Oo':
name = input('Name: ').title()
if name in lstSat:
print(f'{name} already in use')
else:
lbs = int(input('lbs: '))
speed = int(input('Speed: '))
lstSat.append(Satellite(name, lbs, speed))
for satellite in lstSat:
print(satellite)
I would go for iteration in list and check names with every satellite
...
while e=="o":
satellite = Satellite("Info for satellite " + str(i+1))
if check_reapeated_name(lstSat, satellite.name): # see definition of function bellow
lstSat.append(satellite)
else:
# here do some output or error handling
...
...
and the definition of check_reapeated_name() would be something like this:
def check_reapeated_name(lstSat, satellite_name):
for i in lstSat:
if i.name == satellite_name:
return False
return True

Creating class instance based on user input

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!

Python AttributeError:- Main instance has no attribute 'placeName'

class Main():
def __init__(self):
def placeName(self):
place_name = raw_input("\n=> Enter a place name: ")
placename_data = place_name.strip()
if re.match("^[a-zA-Z]*$", placename_data):
return placename_data
else:
print("Error! Only Alphabets from are allowed as input!")
a = Main()
new = a.placeName()
Above code for placeName() method runs correctly without using class but when I try to add it in a class, code gives an attribute error . Can't understand what is wrong here.
You don't need to define __init__ inside the Main class.
class Main():
def placeName(self):
place_name = raw_input("\n=> Enter a place name: ")
placename_data = place_name.strip()
if re.match("^[a-zA-Z]*$", placename_data):
return placename_data
else:
print("Error! Only Alphabets from are allowed as input!")
a = Main()
new = a.placeName()
Please remove __init__ method and try.

Class isn't outputting arguments/doing anything? (Python)

class Fridge:
def __init__ (self, food, quantity):
self.food=food
self.quantity=quantity
def UserEntry(self):
if input=="milk":
print("you got milk!")
else:
print ("What do you want?")
def DisplayFridge(self):
print("Fridge_item#1 :" , self.food, "Quantity:" , self.quantity)
When I attempt to instantiate the class, such as:
test= Fridge
and as soon as a I open the parenthesis in order to instantiate the class such as follows:
test = Fridge (
I am presented with the arguments that were passed to the class constructor/initialization method. (i.e. food and quantity).
With that in mind then....I am at a bit of a loss as to why I am not getting any output. nor, am I being asked for input, etc.
You are not getting any input this way, you should try :
class Fridge:
def __init__ (self, food, quantity):
self.food=food
self.quantity=quantity
def UserEntry(self):
var = raw_input("Please enter something: ")
if var=="milk":
print("you got milk!")
else:
print ("What do you want?")
def DisplayFridge(self):
print("Fridge_item#1 :" , self.food, "Quantity:" , self.quantity)
But there is serious lack of logic in your code :
Why UserEntry is never used ?
How do you use Fridge ?
You userEntry method will never change your self.food variable.
If you're making an instance, you type
test = Fridge(
And then it doesn't show you "the arguments that were passed to the class constructor/initialization method", but it shows you what you have to pass in order to make an instance.
E.g.
test = Fridge("milk", 10)
And now it holds 10 milks. Try
test.UserEntry()
test.DisplayFridge()

Homework Help - Object-Oriented Programming

In my intro class, we just started the section on object-oriented programming. This class is the first I've ever been exposed to programming, and I'm really not understanding it.
We have an assignment where we have to create an Animal class, a Zoo class, and then a zookeeper program to run the information from the first two classes. I have the programs typed up based off of examples in my book, but am still not doing it correctly.
If you could look over my codes and give me some feedback or help, that would be greatly appreciated!
class Animal:
def __innit__(self, animal_type, name):
self.animal_type = animal_type
self.name = name
def get_animal_type(self, animal_type):
self.__animal_type = animal_type
def get_name(self, name):
self.__name = name
def check_mood(self, mood):
input random.txt
print random.random()
Class Zoo:
def __innit__(self):
self.__animals = animal_list
def add_animals(self, animal):
self.__animals.append(animal)
def show_animals(animal_list):
return animal_list
input Animal.py
input Zoo.py
def main():
ADD_ANIMAL = 1
SHOW_ANIMALS = 2
EXIT = 3
def get_manu_choice():
print()
print("Zoo Options")
print("-----------")
print("1. Add Animal")
print("2. Show Animals")
print("3. Exit")
print()
choice = int(input("What would you like to do? "))
while choice < ADD_ANIMAL or choice > EXIT:
choice = int(input("Please choose a valid option: "))
return choice
main()
innit should be init
Looks to me like you are missing a chunk of functionality. You need an instance of zoo, and then in response to the input, either add another animal to the zoo or print the list of animals.

Categories