access variables across different classes using kivy - python

I am trying to access a variables across classes to compare strings. I thought to use a global but that only works if I assign the global a value. I am assigning each variable random string from a list in one class and then doing the same in another class then comparing to see if they match.
class A(screen):
check1 = ""
check2 = ""
check3 = ""
def on_enter(self):
rand_files = ["hello", "goodbye", "what"]
Check1, Check2, Check3 = rand_files
class B(screen):
Ans1 = ""
Ans2 = ""
Ans3 = ""
Ans4 = ""
Ans5 = ""
Ans6 = ""
def on_enter(self):
rand_files = ["hello", "night", "goodbye", "day", "what", "morning"]
Ans1, Ans2, Ans3, Ans4, Ans5, Ans6 = rand_files
def verifyAns1(self):
if Ans1 == Check1 or Ans2 == Check2 or Ans3 == Check3:
print("You got it!!!")
else:
print("Try again")
When I try to do it like this I get the error:
NameError: name 'Ans1' is not defined

You are using class variables in your example. Nothing wrong here, but be aware that if you have multiple instances of these classes, each instance shares the class variables. If one changes a value, the value is changed for all.
If that behavior is not what you are looking for, you probably want to use Python properties.
It is not that one way is necessarily better than the other, it is just how you wish to control the scope of the variables.
That being said, here is an example that may solve your problem using class variables:
class A:
a0 = 0
a1 = 1
a2 = 2
def __init__(self):
print('hello from A')
print(A.a0)
print(B.b2)
class B:
b0 = 3
b1 = 4
b2 = 5
def __init__(self):
print('hello from B')
print(A.a2)
print(B.b0)
A()
B()
And the result:
hello from A
0
5
hello from B
2
3

Related

method not working when i call it from another method for random name gen in python

I am creating a random name generator using OOP in python however i am very new to this concept which is why i am having so difficulties with accessing methods in other methods. I read a post on stack overflow which said to call a method inside another method in a class, you must add self.funcname(param) however i have already done this and it still does not work
class Rndm_nme_gen:
def __init__(self):
print("THE RANDOM NAME GENERATOR")
self.value = ""
self.range = 5
self.counter = 0
self.loop = True
self.names = []
self.loop2 = True
self.take_input()
def take_input(self):
while self.loop:
user_input = input("ENTER A NAME: ")
self.num_check(user_input)
if self.value == "true":
print("INVALID NAME")
loop = True
elif self.value == "false":
self.counter += 1
self.names.append(user_input)
if self.counter == 5:
self.loop = False
self.genname()
#i am trying to call this function but it is not working as i hoped it would
def num_check(self, string):
self.string = string
for char in self.string:
if char.isdigit():
self.value = "true"
else:
self.value = "false"
def genname(self):
while self.loop:
gen = input("TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT").strip().lower()
if gen == " " or gen == "":
num = random.randint(0, 5)
print("NAME : " + str(self.names[num]))
loop == True
elif gen == 'q':
quit()
else:
print("UNKNOWN COMMAND")
loop = True
user1 = Rndm_nme_gen()
In the initialisation method, i called the take_input function so it automatically runs and from that function, i attempted to run the code from the genname function however the program would simply end
If you would like to run the code to see how it works, feel free to do so
Expected output:
ENTER NAME FDSF
ENTER NAME dfsd
ENTER NAME sdfds
ENTER NAME sfdff
ENTER NAME sfdf
TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT
it does not say TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT when i run the program

How to compare 2 objects from a class

I have created a class called Dog_card. With this, I created player_card and computer_card. I am trying to compare the same attribute from both of these objects. There are more values to each than friendliness, but I have removed them so it is easier to test. I keep getting the error:
NameError: name 'player_card' is not defined
Here is my code:
class Dog_card:
def __init__(self):
self.name = ""
self.friendliness = ""
def printing_card(self):
prnt_str = "Name: %s \nIntelligence: %s" %(self.name, self.friendliness)
return prnt_str
def printing_player_card():
player_card = Dog_card()
player_card.name = dogs_list_player[0]
player_card.friendliness = random.randint(1,101)
def printing_computer_card():
computer_card = Dog_card()
computer_card.name = dogs_list_computer[0]
def choose_category():
user_choice_category = input("Please choose a category: ")
if user_choice_category not in ["1", "2", "3", "4"]:
print("Please choose from the options above")
choose_category()
else:
if user_choice_category == "1":
if player_card.friendliness > computer_card.friendliness:
print("Player has won the round!")
elif player_card.friendliness == computer_card.friendliness:
print("It is a Draw!")
Any help would be appreciated
The problem is as it's stated in the error. Basically you are trying to use player_card when it is not defined inside the definition of choose_category(). I suggest you pass the value of player_card to the function like the following
def choose_category(player_card):
or you can define it as an attribute so that it can be accessed by the methods of the same class.
you need to initialize play_card before using it. Maybe you call printing_player_card in order to intnialize before, but as you don't return anything from that function, the created object and the variable player_card only lives in scope of the function. When that function finished, player_card object variable is unknown and the object is destroyed.
if you want player_card (as well as computer_card) survice its function, you need to return it an save it to a variable outside the function code.
Furthermore your function name "printing" is bad, as you don't print anything. You just initialize your object.
Maybe that's what you are aiming at.
class Dog_card:
def __init__(self, name, friendliness=1):
self.name = name
self.friendliness = friendliness
def __str__(self):
return "Name: %s \nIntelligence: %s" %(self.name, self.friendliness)
player_card = Dog_card(dogs_list_player[0], random.randint(1,101))
computer_card = Dog_card(dogs_list_copmuter[0])
def choose_category():
user_choice_category = input("Please choose a category: ")
if user_choice_category not in ["1", "2", "3", "4"]:
print("Please choose from the options above")
choose_category()
else:
if user_choice_category == "1":
if player_card.friendliness > computer_card.friendliness:
print("Player has won the round!")
elif player_card.friendliness == computer_card.friendliness:
print("It is a Draw!")

while loops not working for def() functions

I am trying a program that adds two elements together to make a new one, and you have to make as many elements as you can in this process e.g. https://littlealchemy.com/
But I can't seem to get my definitions to re-run inside of a while loop.
When I run it, it doesn't seem to strip the [] out of the list. What's more, it only runs once and then leaves the terminal blank.
Sorry about the abbreviations, I prefer it like that, but I can change it if needed.
Any help would be appreciated.
Thankyou.
Here is my code:
element1 = ""
element2 = ""
de = [] #discovered elements
ne = "" #new element
o1 = ""
o2 = ""
pne = ""
print("You have unlocked Fire, Water, Earth, and Air")
print("To see your unlocked elements, enter in 'menu' into the 'give the first element' option")
e1 = input("Give the first element ") #element 1
e2 = input("Give the second element ") #element 2
def pnestuff():
pne = str(de); pne.strip("["); pne.strip("]")
def operate(x, y, z):
global e1
global e2
o1 = (x)
o2 = (y)
ne = (z)
if (e1 == o1 and e2 == o2) or (e1 == o2 and e2 == o1):
de.append(ne)
print("You have unlocked "+ne+"!")
print("Your complete element list:")
pnestuff()
print(pne)
e1 = ""
e2 = ""
def menu():
global e1
global e2
if e1 == "menu":
print("You have unlocked:")
pnestuff()
print(pne)
e1 = ""
e2 = ""
#===============================================================================#
while 1:
menu()
operate("fire", "water", "steam")
Overall, your code is a disater. But let's focus on your immediate problem. I would guess it's this:
def pnestuff():
pne = str(de); pne.strip("["); pne.strip("]")
which wants to set the global pne but fails to declare it global, and fails to understand that strings are immutable:
def pnestuff():
global pne
pne = str(de).lstrip("[").rstrip("]")
though a better definition might be:
def pnestuff():
global pne
pne = ', '.join(de)
I forgot to put the two insert elements lines inside the while loop. facepalm. and thankyou everyone for the help with x.join

How to pull a variable from one function to another

def letterChoice():
playerLetter = input('Please choose X or O.').upper()
if playerLetter in ['X','O']:
print('The game will now begin.')
while playerLetter not in ['X','O']:
playerLetter = input('Choose X or O.').upper()
if playerLetter == 'X':
computerLetter = 'O'
else:
computerLetter = 'X'
turnChooser()
def turnChooser():
choice = input("Would you like to go first, second or decide by coin toss?(enter 1, 2 or c) ")
while choice not in ["1","2","c"]:
choice = input("Please enter 1, 2 or c. ")
if choice == 1:
print("G")
cur_turn = letterChoice.playerLetter()
elif choice == 2:
print("H")
else:
print("P")
moveTaker()
I can't figure out how I'm supposed to inherit playerLetter into turnChooser(), I've tried putting playerLetter into the brackets of each function but they don't pass and create an argument error and the print("G") and so on are simply there to see if the code works but whenever I enter 1 or 2 "P" is outputted.
You need to define function Attributes for playerLatter
For EX:
def foo():
foo.playerletter=input('Please choose X or O.').upper()
>>> foo()
Please choose X or O.x
>>> foo.playerLetter
'X'
Accessing from another function
def bar():
variable=foo.playerLetter
print(variable)
>>> bar()
X
>>>
You can always check what Attributes are available for a given function
>>> [i for i in dir(foo) if not i.startswith('_')]
['playerLetter']
>>>
Edit turnchooser() to turnchooser(var), then when calling the function pass the letter to the function like this:
def LetterChoice():
Code...
turnchooser(playerletter)
And,
def turnchooser(var):
Code...
The letter will be placed in a variable called var, which means your code will use the letter as var not playerletter.
Of Course you can change the names to whatever you like.
You could add as many variables to the function however they all should have something assigned to them, aka you can't call the previous function like so:
turnchooser()
Unless you assign it a default value:
def turnchooser(var = 'x')
This way whenever the function is called the value of "var" is x unless stated otherwise.
Note that if you want to pass it from one function to another, u either have to assign the letter to a variable then call the function outside the "LetterChoice" or call it in the definition of "LetterChoice"
Within the function that has the variable in it type:
global variableName
Obviously change variableName to whatever the variable is actually called. Hope this helps!
Tommy
You should try using classes: Python documentation
This should be the code:
class Game:
def __init__(self):
self.cur_turn = ''
self.choise = ''
self.playerLetter = ''
self.computerLetter = ''
def letterChoice(self):
while True:
self.playerLetter = input('Please choose X or O.').upper()
if self.playerLetter in ['X','O']:
print('The game will now begin.')
if playerLetter == 'X':
self.computerLetter = 'O'
else:
self.computerLetter = 'X'
break
else:
print ('Please enter only X or O')
def turnChooser(self):
while True:
self.choice = input("Would you like to go first, second or decide by coin toss? (enter 1, 2 or c) ")
if self.choice in ["1","2","c"]:
if self.choice == 1:
print("G")
self.cur_turn = self.playerLetter()
elif self.choice == 2:
print("H")
else:
print("P")
break
else:
print ('Please enter 1, 2 or c')
game = Game()
game.letterChoice()
game.turnChooser()
# If you want to read any of the variables in Game just write 'self.VARIABLE_NAME'

fix thsi please [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I keep getting errors like this. It is a restaurant code, in which the menu is printed and orders are taken but error is in writing the order and cost in a file text,
I have tried to make a menu in form of dictionary, but can't write the data in text file
class restaurant():
def __init__(self):
self.name = ""
self.menu = {}
self.order = []
self.bill = 0
def print_menu(self):
print "MENU CARD"
self.menu = {'BBQ Grill':'50','Chicken Gollati':'80','French fries':'60',
'Hara Bara Kabab':'90','Makani Special Dum Biriyani':'100',
'Egg Jumbo Sandwich':'120','Roasted Prawn Salad':'90',
'Parathas':'80','Turkish Barbeque Plate':'100'}
for item in self.menu:
print item,"-",self.menu[item]
def takeorder(self):
f1 = open("billlog.txt","w")
print "What would you like to order?"
ans = "y"
while ans == "y":
food = raw_input("enter order - ")
self.bill += int(self.menu[food])
ans = raw_input("go on?(y/n): ")
f1.write(food)
f1.write("\t\t")
f1.write(self.bill)
print food,"\t\t\t",self.bill
f1.close()
def readfilebilllogs(self):
f1 = open("billlog.txt","r")
f1.read()
f1.close()
r = restaurant()
r.print_menu()
r.takeorder()
r.readfilebilllogs()
Your code has multiple errors. Try this it should work. I tried on python3 and modified for python2.7 so there could be some syntax error. I've explained the errors in comment
class restaurant():
def __init__(self):
self.name = ""
self.menu = {}
self.order = []
self.bill = 0
def print_menu(self):
print "MENU CARD"
##This should be self.menu instead of just menu. If you use just menu it's a local variable which can't be used from other function
self.menu = {'BBQ Grill':'50','Chicken Gollati':'80','French fries':'60',
'Hara Bara Kabab':'90','Makani Special Dum Biriyani':'100',
'Egg Jumbo Sandwich':'120','Roasted Prawn Salad':'90',
'Parathas':'80','Turkish Barbeque Plate':'100'}
#Again self.menu
for item in self.menu:
print item,"-",self.menu[item]
def has_item(self):
name = raw_input("Enter name of costumer: ")
food = raw_input("Enter order: ")
for i in self.menu:
if i == food:
print "Yes"
else:
print "No"
# The first parameter is always instance of the class (self).
def takeorder(self):
print "What would you like to order?"
ans = "y"
while ans == "y":
food = raw_input("enter order - ")
# Instead of bill it should be self.bill
#Convert string value of cost to int while adding
self.bill += int(self.menu[food])
ans = raw_input("go on?(y/n): ")
print self.bill
r = restaurant()
r.print_menu()
r.takeorder()
A couple of errors in there:
Turkish Barbeque Plate' this is missing an apostrophe in the beginning.
You defined your fields in the constructor so to use them in other methods inside the class, you need to prefix with self. This is why you need to pass self to all other methods. Also takeorder method needs to be passed self not print_menu.
Your menu items' values are of type str while in this line bill += menu[food] you are adding str to bill which is an int. This is not going to work. Either change values to int or change this line to bill += int(menu[food])
Change line:
bill += menu[food]
into:
self.bill += menu[food]
The first issue I can see is that in your menu variable there is an apostrophe missing before Turkish Barbeque Plate which will break your dictionary.
Secondly, you're referring to bill before its created.
I've fixed up a few things and the following should work.
class restaurant():
def __init__(self):
self.name = ""
self.order = []
self.bill = 0
self.menu = {'BBQ Grill':50,
'Chicken Gollati':80,
'French fries':60,
'Hara Bara Kabab':90,
'Makani Special Dum Biriyani':100,
'Egg Jumbo Sandwich':120,
'Roasted Prawn Salad':90,
'Parathas':80,
'Turkish Barbeque Plate':100}
def print_menu(self):
print ("MENU CARD")
for item in self.menu:
print '{} - {}'.format(item, self.menu[item])
def has_item(self):
name = raw_input("Enter name of customer: ")
food = raw_input("Enter order: ")
for item in self.menu():
if item == food:
print "Yes"
else:
print "No"
def take_order(self):
print "What would you like to order? "
response = 'yes'
while response.lower() == 'yes': #.lower() to remove caps from response
food = raw_input("Enter Order: ")
self.bill += self.menu[food]
response = raw_input("Go on? (Yes or No): ")
print self.bill
r = restaurant()
r.print_menu()
r.take_order()

Categories