I am trying to write a class with 2 functions in Python, like this:
class Arithmetic(Enum):
add = 1
addi = 2
sub = 3
lui = 4
auipc = 5
def parse(inst, *argv):
if inst == "add":
return calculate_add(argv)
elif inst == "addi":
pass
elif inst == "sub":
pass
elif inst == "lui":
pass
elif inst == "auipc":
pass
def calculate_add(*argv):
return argv[0] + argv[1]
and I keep getting this error:
NameError: name 'calculate_add' is not defined. What am I doing wrong?
In your code, you have defined calculate_add after the parse function. So, when you run calculate_add in your parse function, Python does not recognize it, since it hasn't been defined yet.
To fix it, define calculate_add before you define parse.
I believe you must declare the function before trying to access it. 🙂
(It's not cool like Java)
Related
really sorry if someone has asked this before, i just couldn't find what i was looking for, I'm new to coding and aren't sure why i cant get 'matrice2x2mult' function to be called within 'runcalc'. However i suspect it is to do with me calling the function 'runcalc' at the bottom. Any help will be greatly appreciated. Once again sorry.
-I get the error message:
Traceback (most recent call last):
File "FILE_PATH", line 42, in <module>
query.runcalc(q)
File "FILE_PATH", line 19, in runcalc
matrice2x2mult()
NameError: name 'matrice2x2mult' is not defined
import time
class calculator():
def __init__(self, method):
self.method = method
def matrice2x2mult():
print("Matrix 1:")
a = input("a:")
b = input("b:")
c = input("c:")
d = input("d:")
print(f"({a} {b})\n({c} {d})")
def runcalc(self, method):
if self.method == "1":
print("yes")
matrice2x2mult()
elif self.method == "2":
pass
print ("welcome to matrice Calculator: \nEnter 'HELP' for help menu")
time.sleep(1)
q = input(r"What method is required:")
q = str(q)
help1 = False
while help1 == False:
if r"HELP" in str(q):
print("------help-menu------")
print("ENTER '1' FOR 2X2 MATRIX MULTIPLICATION")
print("ENTER '2' FOR A INVERSE OF A 2X2 MATRIX")
time.sleep(1)
q = str(input(r"What method is required:"))
break
else:
break
pass
query = calculator(q)
query.runcalc(q)```
[1]: https://i.stack.imgur.com/s6jud.png
Since matrice2x2mult is defined within calculator, and you're trying to access it via runcalc which is also defined within the same class, you need to use self.matrice2x2mult to access the function. The only way that using just matrice2x2mult would work is either if it was defined in global scope rather than just in that class, or if you did something like matrice2x2mult = self.matrice2x2mult which would be weird and not recommended.
I am trying to access an iterator 'obj' before the 'for' loop like this
class MyClass:
CLASS_CONST1 = 'some_rand_const'
def __init__(self, type, age):
self.type = type
self.age = age
var1 = 5
age = 7
# # I tried to individually add the following lines here, none of them work
# obj = MyClass
# obj = MyClass()
condition = obj.type == MyClass.CLASS_CONST1
if var1 > 10:
condition = obj.type == MyClass.CLASS_CONST1 and obj.age == age
list_of_objects = [MyClass('rand1', 'rand2'), MyClass('rand1', 'rand2'), MyClass('rand1', 'rand2')]
for obj in list_of_objects:
if condition:
# do some stuff
pass
The issue is that it is accessed before it is defined (it gets defined in the for loop). And I dont want introduce the condition lines inside the 'for' loop because the lines would be executed in every iteration, and there is no need for that.
The idea is that all this goes into a function and 'var1' and 'age' are arguments of the function.
obj = MyClass just assigns the class object (not instance) to another variable. obj = MyClass() will throw an error because you haven't provided values for type and age which are required in __init__. Did you try obj = MyClass(var1, age) ? You did it later for list_of_objects.
Anyway, you've tried to create condition as a variable that is supposed to apply itself during the iteration. That's not how Python works. It's given a static value when it's evaluated the one time. To have it apply to all objects, have condition as a function which either take the object or the two variables type and var as parameters and then return the result of the check:
var1 = 5
age = 7
def condition(obj):
# will return the True/False result of the check below
return obj.type == MyClass.CLASS_CONST1 and obj.age == age
for obj in list_of_objects:
if condition(obj): # call the function with that object
# do some stuff
pass
From your code, it's unclear what you wanted in condition. Maybe it was this?
var1 = 5 # or put these inside `condition` so they are local
age = 7 # to condition and not globals.
# Or pass them in as parameters and modify `condition` to accept
# the additional params
def condition(obj):
result = obj.type == MyClass.CLASS_CONST1
if result and var1 > 10:
# don't re-check `obj.type == MyClass.CLASS_CONST1`
result = obj.age == age
return result
You declare condition as a simple boolean variable, while its value has to depend on the current values of obj. You could use a bunch of functions and assign condition to the relevant one, or as you conditions are simple, you could use lambdas:
condition = obj.type == MyClass.CLASS_CONST1
if var1 > 10:
condition = lambda obj: obj.type == MyClass.CLASS_CONST1 and obj.age == age
else:
condition = lambda obj: obj.type == MyClass.CLASS_CONST1
and then use it as a variable function:
for obj in list_of_objects:
if condition(obj):
# do some stuff
pass
I have these two functions:
def check_channel_number(self):
print "***************Channel Checker *********************"
print ''
user_channel_number = int(re.sub('\D', '', raw_input("Enter a channel number, (3digit): "))[:3]);
channel = ("channelNr= '%d'") % (user_channel_number)
print channel
# channel_search = channel + str(user_channel_number)
datafile = file('output.txt')
found = False
for line in datafile:
if channel in line:
found = True
print 'The channel number you entered is correct and will be deleted'
return user_channel_number
print 'The channel number you entered is not on the planner'
return False
and
def delete_events(self):
if user_channel_number == True:
return 'The program number is correct and will be deleted'
# action = 'DeleteEvent'
menu_action = 'all'
book = 'RECYC:687869882'
arg_list = [('C:\\Users\\yke01\\Documents\\StormTest\\Scripts\\Completed'
'\\Utils\\UPNP_Client_Cmd_Line.py')]
arg_list.append(' --action=')
arg_list.append(action)
arg_list.append(' --ip=')
arg_list.append('10.10.8.89')
arg_list.append(' --objectId=')
arg_list.append(book)
subprocess.call(["python", arg_list])
print 'The program deleted successfully'
When I run my script, it says that user_channel_number is not defined globally. How can I use user_channel_number inside the delete_events function?
When you define a variable inside of a function, it is a local variable, meaning that it can only be accessed within that function.
Within a Class
It looks like you're inside a class, so you can make the variable accessible to all methods in the class by defining it like this:
def check_channel_number(self):
self.user_channel_number = ...
And then in your second function, you can use it like the following:
def delete_events(self):
if self.user_channel_number:
Outside of a class
If you aren't using methods inside of a class, you can instead use the global builtin.
For example,
def check_channel_number():
global user_channel_number
user_channel_number = ...
def delete_events():
if user_channel_number:
...
Using a value returned from a function
Instead in your first function, check_channel_number(), you can have it return user_channel_number. You can then call that function inside of delete_events(), like the following:
def check_channel_number():
user_channel_number = ...
return user_channel_number
def delete_events():
if check_channel_number():
...
Functions can not share their local variables. You can return the value from the first and pass it to the second:
def check_channel_number(self):
...
return user_channel_number
def delete_events(self):
user_channel_number = self.check_channel_number()
...
Or save value on the object:
def check_channel_number(self):
...
self.user_channel_number = user_channel_number
...
def delete_events(self):
if self.user_channel_number:
....
So I think when you call the check_channel_number function, user_channel_number is defined in there, so when you call delete_events, it has gone out of scope, maybe something like this would help?
user_channel_number = check_channel_number()
delete_events()
I'd probably have the user_channel_number as an input to the delete function too, so it would turn into this: (where ucn is the user_channel_number)
def delete_events(self, ucn):
if ucn == True:
print 'The program number is correct and will be deleted'
# action = 'DeleteEvent'
menu_action = 'all'
book = 'RECYC:687869882'
arg_list = [('C:\\Users\\yke01\\Documents\\StormTest\\Scripts\\Completed'
'\\Utils\\UPNP_Client_Cmd_Line.py')]
arg_list.append(' --action=')
arg_list.append(action)
arg_list.append(' --ip=')
arg_list.append('10.10.8.89')
arg_list.append(' --objectId=')
arg_list.append(book)
subprocess.call(["python", arg_list])
print 'The program deleted successfully'
I have also changed `return 'The program number is correct and will be deleted'' to a print statement as I have a feeling the return would end the function before the other lines of code would be run
So the code would probably end up being something like:
user_channel_number = check_channel_number()
delete_events(user_channel_number)
EDIT:
just noticed it looks like your functions are part of a class,
in that case, you could do:
self.ucn = self.check_channel_number()
self.delete_events(self.ucn)
(or if you dont want to pass the user_channel_number into the function you could change if user_channel_number: to if self. user_channel_number:
I'm sure there's a simple explanation for this (beyond just that I'm new to Python), but let's say I have two file in the same directory. One is this little script in a file named lexicon.py that checks user input:
def string_checker3(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
raise ValueError
except ValueError:
print "We need a string here!"
return None
def Chipcar_testgreeting(action):
action_split = action.split()
for i in action_split:
strcheck = string_checker3(action)
if strcheck == None:
StartGame
else:
pass
The other script, my main script, is called newGame.py and has a class like this, within which I would like to call the Chipcar_testgreeting(action) function.
from lexicon import *
class ChipCar(Scene):
def enter(self):
print "What's up mothafucka! Get in the Bran Muffin car!"
action = raw_input("> ")
user_test = lexicon.Chipcar_testgreeting(action)
user_test
if(action == "shut up chip" or action == "oh no, it's chip"):
print "forget you!"
print action
return next_scene('Your_death')
#return 'Death'
elif(action == "hi chip" or action == "hello chip"):
print "What's up?!?! Let's go to O&A..."
return next_scene('Chip_in_studio')
else:
print "what's wrong with ya are ya stupid or sumptin? Let's go to my mudda's house, I think Lamar's there..."
return next_scene('Chip_mom_house')
FirstScene = ChipCar()
StartGame = FirstScene.enter()
However, I get this error now:
user_test = lexicon.Chipcar_testgreeting(action)
NameError: global name 'lexicon' is not defined
What am I doing wrong?
As you wrote from lexicon import *, all the importable names from that module are available to you directly (in other words, you don't need lexicon. anymore).
If you write import lexicon, now you have only imported the lexicon name into your module, and you need to use it and the scope-resolution operator (that's the .) to get to the other names of objects inside that module. In this case, you can use lexicon.Chipcar_testgreeting(action).
So, either replace from lexicon import * with import lexicon, or change lexicon.Chipcar_testgreeting(action) to Chipchar_testgreeting(action).
The recommended option is to use import lexicon.
Once you sort that out, you need to resolve another major issue which is this:
if strcheck == None:
StartGame
else:
pass
Not sure what do you expect StartGame to do here, since there is nothing with this name in the lexicon.py module.
I have this method in a class
class CatList:
lista = codecs.open('googlecat.txt', 'r', encoding='utf-8').read()
soup = BeautifulSoup(lista)
# parse the list through BeautifulSoup
def parseList(tag):
if tag.name == 'ul':
return [parseList(item)
for item in tag.findAll('li', recursive=False)]
elif tag.name == 'li':
if tag.ul is None:
return tag.text
else:
return (tag.contents[0].string.strip(), parseList(tag.ul))
but when I try to call it like this:
myCL = CatList()
myList = myCL.parseList(myCL.soup.ul)
I have the following error:
parseList() takes exactly 1 argument (2 given)
I tried to add self as an argument to the method but when I do that the error I get is the following:
global name 'parseList' is not defined
not very clear to me how this actually works.
Any hint?
Thanks
You forgot the self argument.
You need to change this line:
def parseList(tag):
with:
def parseList(self, tag):
You also got a global name error, since you're trying to access parseList without self.
While you should to do something like:
self.parseList(item)
inside your method.
To be specific, you need to do that in two lines of your code:
return [self.parseList(item)
and
return (tag.contents[0].string.strip(), self.parseList(tag.ul))