How to add values to a dictionary of class in python - python

It's my first time posting here. I'm currently facing a problem where my goal is for user to have a command where my dictionary of classes will add exp to the class argument. (I'm kinda bad at english if you want some clarification, Please let me know)
class Stats:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
stre = {1: Stats(name='Excercise', exp=0, description="This is a description"),
2: Stats(name='Gym', exp=0, description="Gym description")}
def statsComm():
command_list = ["stre", "inte", "will"]
print("Select Command {}".format(command_list))
command = input("> ")
if command == 'stre':
for key, value in stre.items():
print(value.exp)
while True:
print("Enter Command {}".format(command_list))
command = input("> ")
if command == 'stats':
statsComm()
Currently it prints the right thing. But I don't know how to add value to exp of an individual class when they enter a command. Thank you :D

You can specify individual classes within the for loop as follows:
for key, value in stre.items():
if value.name == 'Exercise':
value.exp += 1

Related

How do I use an input to print a class definition?

I am trying to code something basic in python just for fun and I encountered an issue,
# Employee is a class with the initialization being self, name, status
e1 = Employee("Tom, Lincoln", "Present")
e2 = Employee("Sam, Bradley", "Absent")
print(e1.status)
# printing e1 status will make "Present" or "Absent"
while True:
try:
cmd = input("Cmd: ")
if cmd == "status_check":
who = input("Who: ")
# putting in e1 or e2 will get their respective statuses
I've tried everything I can think off like, making it so that it gets a number out of the input("Who: ") input so I can better use eval or exac, but doing that makes it so I cant run e1.status because all it has is a 1 and I can't make a "e" appear in front of it so I can't run e1.status. I've also tried using just eval or exac but that didn't get the wanted result because I would have to type my code in the input("Cmd: "). That's isn't the only things I've tried but those are some that come to mind.
I'm just stumped here.
If you want to map names to values, you don't want separate variables. You want a dictionary.
Rather than
e1 = Employee("Tom, Lincoln", "Present")
e2 = Employee("Sam, Bradley", "Absent")
Consider
employees = {
'e1': Employee("Tom, Lincoln", "Present"),
'e2': Employee("Sam, Bradley", "Absent"),
}
To access an employee, write
print(employees["e1"].status)
and then you can use the input string to subscript employees as well.
who = input("Who: ")
print(employees[who].status)
one other approach is to use sys module:
import sys
# class definitions etc
while True:
try:
cmd = input("Cmd: ")
if cmd == "status_check":
who = input("Who: ")
atr = getattr(sys.modules[__name__], who)
print(atr.status)

How to use variable from constructor inside of methode?

Hi guys hope u are doing well, i'm new with python :)
so i have two issues the first how can i use the variable name from the init to my function game() which it use two args (those args whose make it realy difficult for me !) as u can see in code bellow:
# FUNCTION.py
class penGame():
def __init__(self):
print("Welcome to Pendu Game")
self.name = input("Enter your name: ") # IMPORT THIS VARIABLE FROM HERE
def game(self, letter, rword):
letter = letter.lower()
if letter in rword:
for Id, Value in enumerate(rword):
if Value == letter:
donnee.default_liste[Id] = letter
else:
name2 = self.name # it deosn't work i got 1 missing arg when i run the code from MAIN.py
print(f"try again {name} it's wrong ")
print("-".join(donnee.default_liste))
The second issue is i need to use the same variable (name) from init in another module which is my main module and i couldn't use it cause i tried to create an object from class penGame() like:
myObject = penGame()
name2 = myObject.name
then use the name2 inside of the if condition as u can see bellow but it doesn't work properly cause it run the init again which is not what i want actualy !
any idea how can i did it plz?
#MAIN.py
import donnee
from fonctions import penGame
random_word = random.choice(donnee.liste_words) # creation of random word from liste_words
penGame() #call the constructor
while donnee.counter < donnee.score:
letter = input("Enter the letter: ")
if penGame.check(letter):
print("You cant use more one letter or numbers, try again !")
else:
penGame.game(letter, random_word) # as u can see that's the reason cause i supposed to send 3 args instead of two ! but i only need those two !!?
if penGame.check_liste():
myObject = penGame() # that's cause runing the init everytime !!
name2 = myObject.name
print(f"congratulation {name2} you've guessed the word, your score is: {donnee.choice-donnee.counter} point.")
break
if penGame.loser():
print(f"the word was {random_word.upper()} you have done your chances good luck next time.")
donnee.counter += 1
Thank u in advance hope u help me with that and excuse my english if it wasn't that good :) :)
1.Error
You're calling the methods on the class penGame, not on a instance of penGame.
This causes your missing argument error because the method needs an instance of the class (the self parameter) but don't get one.
Instead use your variable (from the second solution):
if mygame.check(letter):
print("You cant use more one letter or numbers, try again !")
else:
mygame.game(letter, random_word)
...
Replace penGame with mygame also in the other calls.
Error
Save the result of the call in a variable and you won't need to recreate it.
mygame = penGame() # call the constructor
This line can then be removed:
myObject = penGame() # that causes the init to run again because it creates a new instance!

How to use a String Input as a Variable Call In Python?

item =["Item_name","Price"]
stop = input("Enter your message: ")
if stop[:3] == "add":
item2 = stop[4:]
I have a code something like this and I want to get the variable item based on a user input. For example, the user types inputs "add item", it should output item[0] and item[1], but I don't know how to do it.
Breaking it down into small pieces is the easiest way to keep it from getting out of hand when you need to add more commands -- trying to parse a command string with slices is going to get complicated quickly! Instead, try splitting the command into words, and then associating each word with the thing you want to do with it.
from enum import Enum
from typing import Callable, Dict
class Command(Enum):
"""All the commands the user might input."""
ADD = "add"
# other commands go here
class Parameter(Enum):
"""All the parameters to those commands."""
ITEM = "item"
# other parameters go here
item = ["Item_name","Price"]
def add_func(param: Parameter) -> None:
"""Add a thing."""
if param == Parameter.ITEM:
print(item)
COMMAND_FUNCS: Dict[Command, Callable[[Parameter], None]] = {
"""The functions that implement each command."""
Command.ADD: add_func,
}
# Get the command and parameter from the user,
# and then run that function with that parameter!
[cmd, param] = input("Enter your message: ").split()
COMMAND_FUNCS[Command(cmd)](Parameter(param))

Variable within an instance of a class does not take a new value when it is assigned.

So, I'm working on a command line RPG for the sake of filling time, and re-stretching my Python muscles as I've been out of practice for a couple of years. I used to code in a really functional manner but I'm trying to get my head around object-orientated programming.
Preamble aside, I have an issue where after creating an instance of a class, my class variable is no longer being defined. I've made 2 versions of this which I'll use to demonstrate since I'm finding it hard to articulate.
Below I created a "character" class which I intended to use as a basis for both player characters and npcs. In the first draft I was updating this class, before realising it was going to affect subclasses, when I really just wanted it as a template. Either way, this particular code block worked; it adds the values of 2 dictionaries together, then assigns them to character.characterStats. It then prints them as per displayStats().
from collections import Counter
class character:
def __init__(self, *args, **kwargs):
pass
def __setattr__(self, name, value):
pass
characterRace = ''
characterStats = {}
charLocation = ''
charName = ''
class race:
def __init__(self):
pass
baseStatsDict = {
'Strength' : 5,
'Agility' : 5,
'Toughness' : 5,
'Intelligence' : 5 }
humanStatsDict = {
'Strength' : 1,
'Agility' : 1,
'Toughness' : 1,
'Intelligence' : 1 }
def displayRace():
print("Race: ", character.characterRace, "\n")
def displayStats():
for stat, value in character.characterStats.items():
print(stat, "=", value)
print("\n")
def raceSelection():
playerInput = input("I am a ")
playerInput
playerLower = playerInput.lower()
while "human" not in playerLower:
if "human" in playerLower:
character.characterStats = dict(Counter(race.baseStatsDict)+Counter(race.humanStatsDict))
character.characterRace = 'Human'
break
playerInput = input()
playerInput
playerLower = playerInput.lower()
playerChar = character()
raceSelection()
displayRace()
displayStats()
And this was the output:
Race: Human
Strength = 6
Agility = 6
Toughness = 6
Intelligence = 6
This however is the new code when I tried to tidy it up and turn the class into the template it was meant to be, and started using the class instance playerChar which for whatever reason can't assign the new value to playerChar.characterStats. playerChar.displayStats() prints the characterRace and characterStats variables as empty, even though they are assigned when the player enters the value human.
from collections import Counter
class character:
characterRace = ''
characterStats = {}
def __init__(self):
pass
def displayRace(self):
print("Race: ", self.characterRace, "\n")
def displayStats(self):
for stat, value in self.characterStats.items():
print(stat, "=", value)
print("\n")
class race:
def __init__(self):
pass
baseStatsDict = {
'Strength' : 5,
'Agility' : 5,
'Toughness' : 5,
'Intelligence' : 5 }
humanStatsDict = {
'Strength' : 1,
'Agility' : 1,
'Toughness' : 1,
'Intelligence' : 1 }
def raceSelection():
playerInput = input("I am a ")
playerInput
playerLower = playerInput.lower()
while "human" not in playerLower:
if "human" in playerLower:
playerChar.characterStats = dict(Counter(race.baseStatsDict)+Counter(race.humanStatsDict))
playerChar.characterRace = 'Human'
break
playerInput = input()
playerInput
playerLower = playerInput.lower()
playerChar = character()
raceSelection()
playerChar.displayRace()
playerChar.displayStats()
So this will output:
Race:
\n
\n
\n
So I know it's able to draw from the class race dictionaries and add their contents together as from the previous code. If I try and print the player.x characteristics it won't throw any errors so it recognises they exist. If anyone could explain to me what's going wrong and why in this new iteration, I'd be very grateful.
EDIT: So a friend and I have tried passing the class as an argument of raceSelection(), we've tried printing a string after each call/update of a variable and we've tried entering a string into the variable, printing it, then redefining the variable with a new string.
Input:
class character:
charRace = ''
charStats = {}
charLocation = ''
charName = ''
charString = "Cole said define a string."
Within the if statements:
if "human" in playerLower:
print("Oh, you're just a really ugly human.")
playerChar.charStats = dict(Counter(race.baseStatsDict)+Counter(race.humanStatsDict))
playerChar.charRace = 'Ugly Human'
print("playerChar.charString = ", playerChar.charString)
playerChar.charString = "Redefine."
print("playerChar.charString = ", playerChar.charString)
break
Output:
Oh, you're just a really ugly human.
playerChar.charString = Cole said define a string.
playerChar.charString = Cole said define a string.
Race:
It should not be character.characterStats.items(), but self.characterStats.items(). Similarly for all other values that belong to one, specific character.
Using the name of the class assigns a value that belongs to the class, and is the same for all objects you create. Lookup instance vs class attributes.
So, after trying to move the variables in and out of __init__, trying setattr(), trying to pass any sort of argument through the class just so it had some data, trying to run the instance of the class through a function, none of those solutions came to work in the end.
The solution turned out to be to create a subclass of character and manipulate that instead. I figured this would be alright as well since the player character will mutate throughout gameplay, and will never see further subclasses of itself.

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

Categories