Name Error in python [duplicate] - python

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

Related

beginner coding question about end of this code [duplicate]

This question already has answers here:
What does if __name__ == "__main__": do?
(45 answers)
Closed 2 years ago.
What does the last part of this code do exactly? Also why is self.name equal to name? here is the code below:
class Shark:
def __init__(self, name):
self.name = name
def swim(self):
print(self.name + " is swimming.")
def be_awesome(self):
print(self.name + " is being awesome.")
def main():
sammy = Shark("Sammy")
sammy.be_awesome()
stevie = Shark("Stevie")
stevie.swim()
if __name__ == "__main__":
main()
Firs part of your question is answered here
Second question
name is the argument passed when creating a instance of your class. However self.name is a instance variable. The value of this is set to name. Read more about python classes here
The last part of the code:
if __name__ == "__main__":
main()
simply means that when this particular script is run as the entry point file, it will execute the main() function. If the contents are imported by another script, it will ignore the if statement.
self.name = name
assigns the input variable name to the instance variable of the class, in this case it is also called name

How to pass outer function class to inner class? [duplicate]

This question already has an answer here:
How to access outer attribute class within inner class?
(1 answer)
Closed 3 years ago.
As a title, I have a versatility function in parent class that will share use in child class A.k.A inner class. In below, I need to pass outer_send function from parent class. then, use it with call inner_send function inside Identify class alias child class. The result will output Test.
class Device:
def __init__(self):
self.identify = self.Identify(self.outer_send())
def outer_send(message):
print(message)
def last_error(self):
return self.identify.error_info
class Identify:
def __init__(self, send):
self.inner_send() = send()
def set_error(self, error):
self.error_info = error
device = Device()
device.identify.inner_send('test')
I don't like the pattern and I would recommend designing it differently. However, this does what I think you want to do:
class Device:
def __init__(self):
self.identify = self.Identify(self._send)
def _send(self, message):
print(message)
class Identify:
def __init__(self, _send):
self.send = _send
device = Device()
device.identify.send('test')
A few notes: I renamed outer_send to _send, as I assume you don't want people calling that directly on the Device object - if you do, just rename it send and it still works; the error bit seemed superfluous, so left it out; your outer_send was missing self as a parameter - it doesn't need it, but if you do want to leave it out, annotate the method with #staticmethod to avoid warnings.

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

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()

Method takes no arguments [duplicate]

This question already has answers here:
class method with no arguments produces TypeError
(3 answers)
Closed 6 years ago.
class Person:
def __init__(self, name):
self.name = name
def printName():
print "my name is %s" % self.name
Mitchell = Person("Mitchell")
Mitchell.printName()
This code throws this error:
Traceback (most recent call last):
File "/home/mitch/Desktop/test.py", line 8, in <module>
Mitchell.printName()
TypeError: printName() takes no arguments (1 given)
I'm sure I did this correctly...
you missed the self param in the printName function definition
class Person:
def __init__(self, name):
self.name = name
def printName(self):
print "my name is %s" % self.name
Because you forgot to add self explicitly to printName instance method. It should have been like
def printName(self):
...
Python implicitly passes object instance to every instance method. Although not directly related to the question, try to use pep8 conventions when you are working with Python. According to pep8 function names are snake-cased not camel-cased and so are variable names. So use print_name and `mitchell' instaed of their camel and pascel-cased counterparts.

Python: Call a constructor whose name is stored in a variable [duplicate]

This question already has answers here:
Referring to class names through strings?
(5 answers)
Closed 9 years ago.
I have the following variable:
var = 'MyClass'
I would like to create an object of MyClass based on the variable var. Something like var(). How can I do this in Python?
>>> def hello():
... print "hello world"
...
>>> globals()["hello"]()
hello world
Presuming you have the class' module as a variable as well, you can do the following, where the class you want "MyClass" resides in module "my.module":
def get_instance(mod_str, cls_name, *args, **kwargs):
module = __import__(mod_str, fromlist=[cls_name])
mycls = getattr(module, cls_name)
return mycls(*args, **kwargs)
mod_str = 'my.module'
cls_name = 'MyClass'
class_instance = get_instance(mod_str, cls_name, *args, **kwargs)
This function will let you get an instance of any class, with whatever arguments the constructor needs, from any module available to your program.

Categories

Resources