I would like to know how to call one global variable with two different values in a class and call them in the other class (within which behave such as flags).
in SerialP.py
Class SerialP(object):
def ReceiveFrame (self, data, length):
global myvariable
if x:
myvariable = 1:
elif y:
myvariable = 2
in fmMain.py
Class fmMain:
def OnReadConfig(self, event):
if SerialP.myvariable = 1:
#do this task
if SerialP.myvariable = 2:
#do another task
There are a few issues with your code.
First, comparison is done with == and not with = which is used for assignment. Also, you have not included the import statement which might be misleading.
In fmMain.py
import SerialP # and not from SerialP import SerialP
Class fmMain:
def OnReadConfig(self, event):
if SerialP.myvariable == 1: # changed to ==
#do this task
if SerialP.myvariable == 2: # changed to ==
#do another task
Related
I have a class which takes in a user choice (below)
from MiniProject1.interfaces.s_selection import SecondarySelection as SS #
imports the secondary_selection function from selections
import MiniProject1.interfaces.newcastle_cm as IT
from MiniProject1.Newcastle.newcastle_cc import ColumnCalculation as CC
class Newcastle:
def __init__(self):
self.key_typed = input(str("Select what you want to do: "))
#staticmethod
def column_or_graph():
if SS.get_input(SS.display_input()) is True:
IT.column_manipulation()
return True
IT.graph_plotting()
return False
def column_selection(self):
if self.key_typed == 1:
CC.total_electricity() # Calls the total_electricity method
elif self.key_typed == 2:
pass
elif self.key_typed == 3:
pass
elif self.key_typed == 4:
pass
elif self.key_typed == 5:
pass
def main():
if Newcastle.column_or_graph() is True:
Newcastle.column_selection(Newcastle())
elif Newcastle.column_or_graph() is False:
Newcastle.graph_plotting(Newcastle())
if __name__ == "__main__":
main()
The first part seems to run without issue, as the imported functions SS.get_input(SS.display_input()) from a class work without any issues and return either True or False, and when they do Newcastle.column_selection(Newcastle()) works as well, as it displays the interface and takes the user input.
So, all that seems to work. But when the user selects 1 it should return the CC.total_electricity() method, but instead it just ends the program.
I've tried return CC.total_electricity() as well, but that just does the same thing as well, and doesn't work. Is there any idea to why this may be? I've been working on it all day.
The CC.total_electricity class method looks like this:
import pandas as pd
class ColumnCalculation:
"""This houses the functions for all the column manipulation calculations"""
#staticmethod
def total_electricity():
"""Calculates the total amount of electricity used per year"""
df = pd.read_csv("2011-onwards-city-elec-consumption.csv", thousands=',')
df.set_index('Date', inplace=True) # Sets index to months
df.loc['Total'] = df.sum() # Creates a new row for the totals of each year
return print(df) # Prints the dataframe
And that has been tried, and tested to work, it's just when I import it it doesn't return anything and ends the program.
You compare the user input to an integer:
if self.key_typed == 1:
Therefore, you need to convert your input into an integer too.
So instead:
self.key_typed = input(str("Select what you want to do: "))
do:
self.key_typed = int(input("Select what you want to do: "))
This is probably has a very solution but I am struggling with this a bit.
I have 3 almost similar functions I'd like to refactor into one.
Here's the function:
def delete_labels_replication_controller(provider, obj_type):
obj_label_list = []
obj_type_list = provider.mgmt.list_replication_controller()
def delete_labels_node(provider, obj_type):
obj_label_list = []
obj_type_list = provider.mgmt.list_node()
def delete_labels_image(provider, obj_type):
obj_label_list = []
obj_type_list = provider.mgmt.list_image()
Now, as you see, the only thing that changes is the provider.mgmt.xxx class and it changes according to the obj_type I want to pass into the function.
Question is how to use only 1 function for all of them and replace only the .xxx part of the object?
Thanks!
I am sure there is a better solution but maybe using getattr like this?
def delete_labels_by_type(obj_type):
obj_type_list = getattr(provider.mgmt, obj_type)()
return obj_type_list
Do like this
def myFunction(provider, obj_type, flag_type)
obj_label_list = []
if flag_type == 1:
obj_type_list = provider.mgmt.list_replication_controller()
elif flag_type == 2:
obj_type_list = provider.mgmt.list_node()
elif flag_type == 3:
obj_type_list = provider.mgmt.list_image()
You could just pass the obj_type_list as another parameter to the function:
def delete_labels(provider, obj_type, obj_type_list):
obj_label_list = []
...
and then call like this delete_labels(provider, obj_type, provider.mgmt.list_replication_controller()) (and if that's the only time you need the provider parameter, you can remove it entirely)
Or pass a reference to the getter method:
def delete_labels(provider, obj_type, getter):
obj_label_list = []
obj_type_list = getter(provider.mgmt)
...
and then call like this: delete_labels(provider, obj_type, MgmtClass.list_replication_controller)
In both cases, you can move the bulk of the three functions (the common part not shown in the question) into that new function and keep the original functions for easier usage:
def delete_labels_replication_controller(provider, obj_type):
return delete_labels(provider, obj_type, provider.mgmt.list_replication_controller())
I have a sub program that uses a def option, so if i ever want to repeat the program. Eg:
def op1():
print ("Something Something")
So I just write in the program:
op1()
which makes the program run.
Now I have a lot of subprograms each one with a different def so I can run them by easily.
eg:
def op1():
def op2():
def op3():
So I wanted to know how can I use this in if-else statement.
eg:
option = input ("Enter either A, B or C here: ")
if option == A:
def op1():
else:
def op2():
or even
if option == A:
def op1():
elif:
def op2():
elif:
def op3():
Something like that, but it doesn't work. Can anyone help, Please?
Also I'm using the newer version of python if that helps 3.5.0.
You do not need to define functions conditionally.
def op1():
print('1')
def op2():
print('2')
def op3():
print('3')
if option == 'A':
op1()
elif option == 'B'::
op2()
else:
op3()
You need to define your functions first but if you have multiple choices you can store references to functions in a dict then call based on what the user enters, using dict.get with a default function will act like your if/elif else logic:
def op1():
return '1'
def op2():
return '2'
def op3():
return "3"
option_fs = {"A": op1, "B": op2}
option = input("Enter either A, B or C here: ").upper()
print(option_fs.get(option, op3)())
My code looks like:
def g_b():
items_in_bag = []
done=False
bugout_bag = 'Bug Out Bag'
while done == False:
item = input('What bags do you have? [Enter x to stop]')
items_in_bag.append(item)
if item == 'x':
done = True
items_in_bag.remove('x')
break
else:
continue
items_in_bag.append(bugout_bag)
print("Your bags\n")
print(items_in_bag)
return items_in_bag
def g_c():
coins_in_bag = []
done=False
while done == False:
coin_item = input('What coins do you have? [Enter x to stop]')
if coin_item == 'x':
done = True
break
else:
coins_in_bag.append(coin_item)
continue
print("Your coins\n")
print(coins_in_bag)
return coins_in_bag
def a_c_t_b(items_in_bag, coins_in_bag):
#print('Here are your coins:\n')
#g_c()
#print('Here are your bags:\n')
#print(items_in_bag)
print (items_in_bag,coins_in_bag)
return (items_in_bag,coins_in_bag)
def main():
g_b()
g_c()
a_c_t_b(items_in_bag,coins_in_bag)
main()
However, when i run this code like: import myfile
It gives me an error of:
File ".\myfile.py", line 51, i
a_c_t_b(items_in_bag,coins_in_bag)
NameError: global name 'items_in_bag' is not defined
I'm simply trying to return the values of items_in_bag,coins_in_bag from their respective functions.
Thank you
Please call your functions more sensible names.
To answer your question, your g_b and g_c functions return values, they don't return names. At the point where you call a_c_t_b, Python has no idea what items_in_bag is, because yo'uve never defined it. Python can't know you mean "the value returned from g_b": you have to tell it.
items_in_bag = g_b()
coins_in_bag = g_c()
a_c_t_b(items_in_bag, coins_in_bag)
You are calling g_b and g_c but never catching their returned values.
You can either do:
def main():
items_in_bag = g_b()
coins_in_bag = g_c()
a_c_t_b(items_in_bag, coins_in_bag)
or:
def main():
a_c_t_b(g_b(), g_c())
When you import the module main function is executed (call in last line). And main function use undefined identifiers items_in_bag and coins_in_bag:
def main():
g_b()
g_c()
a_c_t_b(items_in_bag,coins_in_bag)
Probably you want something like
def main():
items_in_bag = g_b()
coins_in_bag = g_c()
a_c_t_b(items_in_bag,coins_in_bag)
As the title says, how do you call a function in a class of another program?
Class.py
class Object:
def __init__(self, mood):
self.__mood = mood
def set_mood(self, mood):
self.__mood = mood
def check_mood(self):
if random.randint(1, 3) == 1:
self.__mood = 'happy'
elif random.randint(1, 3) == 2:
self.__mood = 'hungry'
elif random.randint(1, 3) == 3:
self.__mood = 'sleepy'
def get_mood(self):
return self.__mood
Generator.py
from test import Object
import test
mood = 'happy'
ani = Object.test(mood)
print("This is your mood: " + get_mood())
Mood is set as a default value of "happy". I need that to change based on the random integer roll in test so that when mood is displayed, it isn't always displayed as "happy"
You have to explicitly call check_mood to change the object's attribute. See code below.
from random import randint
class Foo(object):
def __init__(self, mood):
self.__mood = mood
self.__selection = {
1:'happy',
2:'hungry',
3:'sleepy',
4:'angry',
5:'bored'
}
def check_mood(self):
m = randint(1,5)
self.__mood = self.__selection[m]
def get_mood(self):
return self.__mood
mood = 'happy'
f = Foo(mood)
print 'This is your previous mood:', f.get_mood()
f.check_mood() # This rerolls the mood.
print 'This is your current mood:', f.get_mood()
# This is your previous mood: happy
# This is your current mood: bored
Otherwise, if you want it to change "behind-the-scenes", I suggest calling check_mood inside get_mood (or just get rid of check_mood entirely and put its code inside get_mood).
However, the way get_mood is defined makes it modify the original self.__mood, rendering the original passed-in argument as lost once you call get_mood.
There are... a lot of problems with this. Lets start with your Object class. You probably don't want to name something Object - it is too similar to object the Python builtin, and doesn't provide any real information about what the class does. Additionally, you probably don't want to call the instance variable __mood - this will invoke name mangling which is probably not something you want. You probably don't even want the single underscore; that represents a "private" data member (and there isn't a clear reason why this should be private). You don't need getter and setter functions in Python because you can access attributes directly, but if you do want finer grained control use a property instead. Lastly, we don't need to keep redefining the random variable in your check_mood function - in fact it will probably introduce bugs. Lets look at this alternate definition instead.
person.py
import random
class Person(object):
_mood = None
def __init__(self, mood):
self.mood = mood
#property
def mood(self):
return self._mood
#mood.setter
def mood(self, new_mood):
self._mood = new_mood
def check_mood(self):
rand_mood = random.randint(1, 3)
if rand_mood == 1:
self.mood = 'happy'
elif rand_mood == 2:
self.mood = 'hungry'
else:
self.mood = 'sleepy'
That's a little better. Lets look at your other file now.
from person import Person
myPerson = Person("happy")
print("This is your mood: ", myPerson.mood)
This should print out the mood of the Person.
In your code you don't ever create an instance of an Object - you just call some test() function on your Object class, not an instance of it. Then when you called get_mood() it doesn't work because that is an instance function - it can only be called on instances of your Object class.