Python 3 : NameError: name 'functionName' is not defined [duplicate] - python

This question already has answers here:
How can I call a function within a class?
(2 answers)
Closed 6 years ago.
I am new in programming and I have faced a problem for which I can't find an answer... So here it is:
`class MyClass:
def printsmth():
print("Hello")
def main():
printsmth()
if __name__ == '__main__':main()`
I get an error which says :
Traceback (most recent call last):
File "untitled.py", line 1, in <module>
class MyClass:
File "untitled.py", line 6, in MyClass
if __name__ == '__main__':main()
File "untitled.py", line 5, in main
printsmth()
NameError: name 'printsmth' is not defined
Code included is just an example, but it is the same error that I get on my real code, if for example I would transfer my code from main() to if name == 'main' than it works perfectly. The thing is that I want to relaunch main() method in some parts of the code but I haven't even gone to that because I can't think of a solution to this error:/ Can you help me?
P.S I tried to move main() and if name == 'main' from MyClass and it didn't worked.

You are forgetting to pass self as the first parameter of your methods. Once you do this, you can callself.printsmth() as a method. Right now it's confused because you're calling it as a function rather than a method.
class MyClass:
def printsmth(self):
print("Hello")
def main(self):
self.printsmth()

Related

AttributeError: 'PigMan' object has no attribute 'iAmFool' in Multithreading

I wrote a short example because I can't share my original codes.
I think the problem was caused by python itself.
Anyway, when I start a thread for a class, the program crashes if there are conditions. What is the reason? What is also the possible solution.
from threading import Thread
global dicta
dicta={"number":0,"name":"John","animal":"pig"}
class PigMan:
def __init__(self):
Thread(target= self.iAmFool).start()
def iAmFool(self):
if dicta["number"]==0:
print("It's work")
else:
print("Wtf")
PigMan()
I expected it to run smoothly, but this is the error:
Traceback (most recent call last):
File "C:/Users/Pig/Desktop/test.py", line 13, in <module>
PigMan()
File "C:/Users/Pig/Desktop/test.py", line 6, in __init__
Thread(target= self.iAmFool).start()
AttributeError: 'PigMan' object has no attribute 'iAmFool'
Your indentation is off. Python is whitespace-sensitive, thus the indentation of your code is critically important.
Reducing def iAmFool's indentation correctly creates it as part of the class PigMan, as opposed to trying to def it within __init__.
from threading import Thread
global dicta
dicta={"number":0,"name":"John","animal":"pig"}
class PigMan:
def __init__(self):
Thread(target= self.iAmFool).start()
def iAmFool(self):
if dicta["number"]==0:
print("It's work")
else:
print("Wtf")
PigMan()
Repl.it

Python function calling order

How does Python "read in" a program when you run it? For example, I don't understand why there wouldn't be a NameError: name 'cough' is not defined in the below code:
def main():
for i in range(3):
cough()
def cough():
print('cough')
if __name__ == '__main__':
main()
Basically, my question can also be stated as why do the above and below programs output the same thing:
def cough():
print('cough')
def main():
for i in range(3):
cough()
if __name__ == '__main__':
main()
Python is an interpreted language which is executed statement by statement
(thanks to viraptor's tip: when compiling to bytecode it happens on whole file + per function)
In this case below the program reads line by line and knows that the function cough() and main() are defined. and later when main() is called Python knows what it is and when main() calls cough() Python knows what it is as well.
def cough():
print('cough')
def main():
for i in range(3):
cough()
if __name__ == '__main__':
main()
In this other case (below) it is the same thing. just that Python learns what main() function is before cough(). Here you might wonder: "why won't python throw an error since it doesn't know what caugh() is inside main() ? " Good question my friend.
But as long as your function is defined before you call it everything is fine. Because remember Python won't "check" if a function is defined until you call it. so in this case even tho cough() is not defined when python is reading function main() it is ok because we didn't call main() until after cough() is defined below.
def main():
for i in range(3):
cough()
def cough():
print('cough')
if __name__ == '__main__':
main()
Hope this helps you understand Python better.
The piece of code preventing the error to happen is this one:
if __name__ == '__main__':
main()
because you are putting it at the end of the code, after python read all the code above.
If you try to write something like
def main():
for i in range(3):
cough()
if __name__ == '__main__':
main()
def cough():
print('cough')
All you are going to get is this:
NameError: name 'cough' is not defined
When Python encounters a function while executing your source code, it does not immediately run the function. Rather, it compiles the function into an executable code object, and waits until you actually call the function.
This means the only time Python checks that cough() is really defined, is when you call main(). And since Python does find a cough function when main is called, it does not raise an error.
In other-words: Python does not verify the names used in function actually exist until run-time, so you so allowed to use currently undefined variable names.
This is the same reason a function such as this doesn't raise an error when defined, but it does during run-time:
>>> def func():
a + b
>>> func # func was compiled...
<function func at 0x7f8ddd5d6488>
>>> func() # but we cannot call it.
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
func() # but we cannot call it.
File "<pyshell#7>", line 2, in func
a + b
NameError: name 'a' is not defined
>>>
Also note that if you try to call main before cough has been defined, you will get an error:
>>> def main():
for i in range(3):
cough()
>>> main()
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
main()
File "<pyshell#12>", line 3, in main
cough()
NameError: name 'cough' is not defined
>>>
This shows that Python relies on every name in your function to have already been defined whether globally or locally, before you attempt to use them.
Python reads from the top of your script to the bottom. In both examples, the cough() function is called after it has been defined.
When you defined main() with cough() inside, the cough() function is not actually run. It is not run until the last line - that is after they have already been defined.
That's because the real execution code is here
if name == 'main':
main()
when main() is called, both main and cough have been defined

Name Error in python [duplicate]

This question already has an answer here:
Python: NameError: global name 'foobar' is not defined [duplicate]
(1 answer)
Closed 7 years ago.
I am getting the following Name Error in my python program though I declared the function before it is used.
Here is my program:
def __init__(self):
self.root = None
def insert_at(leaf, value):
#some code here....
def insert(self,value):
#some code here....
insert_at(self.root, value)
def main():
#some code here
insert(10)
#some code here
Here is my error:
File "programs/binary_tree.py", line 38, in insert
insert_at(self.root, value)
NameError: name 'insert_at' is not defined
I did go through the following questions before asking this question, but couldn't understand why I am getting the error.
Make function definition in a python file order independent
and
Python NameError: name is not defined
Looks like those are methods in a class. You need the following changes:
def insert_at(self, leaf, value): # add self
self.insert_at(self.root, value) # add self

Python class can't see method unless I comment out __init__

The following code only works if I comment out the initialiser.
class What:
def __init__(self):
pass
def method1(self):
print 'method1'
def main():
b = What()
if hasattr(b,"method1"):
print "b.method1"
b.method1()
main()
If it's not commented out I get the error message…
Traceback (most recent call last):
File "strange.py", line 17, in <module>
main()
File "strange.py", line 15, in main
b.method1()
AttributeError: What instance has no attribute 'method1'
However if I type in an identical method and call it, there is no problem at all…
def method2(self):
print 'method2'
I've od -c the file and there are no strange characters in the text
Using Python 2.7.2
I think you are mixing tabs and spaces.
With the code using 4 spaces per indent (spaces in accordance with pep8) it works fine. But this
class What:
def __init__(self):
pass
def method1(self):
print 'method1'
def main():
b = What()
if hasattr(b,"method1"):
print "b.method1"
b.method1()
main()
Is what Python would see if you had tabs for method1, and this will generate the error you see.

"<method> takes no arguments (1 given)" but I gave none [duplicate]

This question already has answers here:
"TypeError: method() takes 1 positional argument but 2 were given" but I only passed one
(10 answers)
Closed 6 months ago.
I am new to Python and I have written this simple script:
#!/usr/bin/python3
import sys
class Hello:
def printHello():
print('Hello!')
def main():
helloObject = Hello()
helloObject.printHello() # Here is the error
if __name__ == '__main__':
main()
When I run it (./hello.py) I get the following error message:
Traceback (most recent call last):
File "./hello.py", line 13, in <module>
main()
File "./hello.py", line 10, in main
helloObject.printHello()
TypeError: printHello() takes no arguments (1 given)
Why does Python think I gave printHello() an argument while I clearly did not? What have I done wrong?
The error is referring to the implicit self argument that is passed implicitly when calling a method like helloObject.printHello(). This parameter needs to be included explicitly in the definition of an instance method. It should look like this:
class Hello:
def printHello(self):
print('Hello!')
If you want printHello as instance method, it should receive self as argument always(ant python will pass implicitly) Unless you want printHello as a static method, then you'll have to use #staticmethod
#!/usr/bin/python3
import sys
class Hello:
def printHello(self):
print('Hello!')
def main():
helloObject = Hello()
helloObject.printHello() # Here is the error
if __name__ == '__main__':
main()
As '#staticmethod'
#!/usr/bin/python3
import sys
class Hello:
#staticmethod
def printHello():
print('Hello!')
def main():
Hello.printHello() # Here is the error
if __name__ == '__main__':
main()
Calling a method on the instance of an object returns the object itself (usually self) to the object. For example, calling Hello().printHello() is the same as calling Hello.printHello(Hello()), which uses an instance of a Hello object as the first argument.
Instead, define your printHello statement as def printHello(self):

Categories

Resources