NameError: global name 'myExample2' is not defined # modules - python

Here is my example.py file:
from myimport import *
def main():
myimport2 = myimport(10)
myimport2.myExample()
if __name__ == "__main__":
main()
And here is myimport.py file:
class myClass:
def __init__(self, number):
self.number = number
def myExample(self):
result = myExample2(self.number) - self.number
print(result)
def myExample2(num):
return num*num
When I run example.py file, i have the following error:
NameError: global name 'myExample2' is not defined
How can I fix that?

Here's a simple fix to your code.
from myimport import myClass #import the class you needed
def main():
myClassInstance = myClass(10) #Create an instance of that class
myClassInstance.myExample()
if __name__ == "__main__":
main()
And the myimport.py:
class myClass:
def __init__(self, number):
self.number = number
def myExample(self):
result = self.myExample2(self.number) - self.number
print(result)
def myExample2(self, num): #the instance object is always needed
#as the first argument in a class method
return num*num

I see two errors in you code:
You need to call myExample2 as self.myExample2(...)
You need to add self when defining myExample2: def myExample2(self, num): ...

First, I agree in with alKid's answer. This is really more a comment on the question than an answer, but I don't have the reputation to comment.
My comment:
The global name that causes the error is myImport not myExample2
Explanation:
The full error message generated by my Python 2.7 is:
Message File Name Line Position
Traceback
<module> C:\xxx\example.py 7
main C:\xxx\example.py 3
NameError: global name 'myimport' is not defined
I found this question when I was trying to track down an obscure "global name not defined" error in my own code. Because the error message in the question is incorrect, I ended up more confused. When I actually ran the code and saw the actual error, it all made sense.
I hope this prevents anyone finding this thread from having the same problem I did. If someone with more reputation than I wants to turn this into a comment or fix the question, please feel free.

You have to create an instance of the myClass class, and not the instance of the whole module(and i edit variables names to be less awful):
from myimport import *
def main():
#myobj = myimport.myClass(10)
# the next string is similar to above, you can do both ways
myobj = myClass(10)
myobj.myExample()
if __name__ == "__main__":
main()

While the other answers are correct, I wonder if there is really a need for myExample2() being a method. You could as well implement it standalone:
def myExample2(num):
return num*num
class myClass:
def __init__(self, number):
self.number = number
def myExample(self):
result = myExample2(self.number) - self.number
print(result)
Or, if you want to keep your namespace clean, implement it as a method, but as it doesn't need self, as a #staticmethod:
def myExample2(num):
return num*num
class myClass:
def __init__(self, number):
self.number = number
def myExample(self):
result = self.myExample2(self.number) - self.number
print(result)
#staticmethod
def myExample2(num):
return num*num

Related

Python - Accessing object variables within a module

I have a module (a python file, that is) containing different classes with functions, here called 'Experiment_1'. When running it as the main file, all objects can access all variables - object_2 functions can access variables in object_1, and so on:
# Experiment_1
class A():
def process1(self):
self.x=10
def process2(self):
self.y=20
class B():
def addition(self):
summed=object_1.x+object_1.y
print(summed)
if __name__ == '__main__':
object_1=A()
object_2=B()
object_1.process1()
object_1.process2()
object_2.addition()
Next, I attempt to run this in file 'Experiment_2' as an imported module:
# Experiment_2
from Experiment_1 import *
import Experiment_1
object_1=A()
object_2=B()
object_1.process1()
object_1.process2()
object_2.addition()
And get the error message:
File "C:\Program Files\Sublime Text 3\Experiment_2.py", line 10, in <module>
object_2.addition()
File "C:\Program Files\Sublime Text 3\Experiment_1.py", line 10, in addition
summed=object_1.x+object_1.y
NameError: name 'object_1' is not defined
Thus, object_2 can no longer access the variables of object_1. I have been searching a lot to find a solution to this but may be using the wrong keywords or simply lack the understanding to recognize the answer when I see it - can anyone give me a hint how to proceed?
Thanks in advance!
When you import a module, the block starting with if __name__ == "__main__": does not get executed as the name variable of the module is set to the name you imported it ("Experiment_1" in this case). From official documentation:
When a Python module or package is imported, name is set to the module’s name. Usually, this is the name of the Python file itself without the .py extension
If you'd like your code to get executed regardless of it is imported or run directly from command line, just place it at the bottom.
The issue is your object instantiation in Experiment_1.py. The code inside the below block only get executed if you run the file as a script and NOT when you import it.
if __name__ == '__main__':
pass
So in your object of class B, the below statement in addition method,
#Experiment_1.py
summed=object_1.x+object_1.y
see object_1 as not defined, because it is only instantiated in the if __name__ == '__main__': block which is not executed when importing the module.
See this question: What does if __name__ == "__main__": do?
And for the solution, If you wish to use the module structure, the work around is to pass the object to the addition method.
#Experiment_1.py
class A():
def process1(self):
self.x = 10
def process2(self):
self.y = 20
class B():
def addition(self, obj):
summed = obj.x + obj.y
print(summed)
then in your next file,
from Experiment1 import *
# import Experiment1
object_1=A()
object_2=B()
object_1.process1()
object_1.process2()
object_2.addition(object_1)
Not tested, but I think the following script is the solution, because you need to inherit attributes. Test changes (on first module) and give a response, please.
class A():
def __init__(self):
self.x = 0
self.y = 0
def process1(self):
self.x=10
def process2(self):
self.y=20
class B(A):
def __init__(self):
A.__init__(self)
def addition(self):
summed = self.x + self.y
print(summed)
if __name__ == '__main__':
object_1 = A()
object_2 = B()
object_1.process1()
object_1.process2()
object_2.addition()
Edit
Sorry, I don't realize that B can do all purpose. This is the good solution:
experiment1.py
class A:
def __init__(self):
self.x = 0
self.y = 0
def process1(self):
self.x = 10
def process2(self):
self.y = 20
class B(A):
def __init__(self):
A.__init__(self)
def addition(self):
summed = self.x + self.y
print(summed)
if __name__ == '__main__':
object_1 = B()
object_1.process1()
object_1.process2()
object_1.addition()
experiment2.py
from Experiment1 import *
if __name__ == '__main__':
object_1 = B()
object_1.process1()
object_2.process2()
object_2.addition()
Explaination: because B class inherits methods and attributes of A class, you don't need instantiate A class. All the work can be run by B class.
As other user said, in B class you are using global variable declared in main section that is unreachable when you import module, this is the principle of the if __name__ == '__main__':

Python - Help on genetic algorithm error

I've been trying to create a genetic algorithm in python but i either get:
<bound method Environment.bestsol of <__main__.Environment instance
at 0x10a5d4ab8>>
or it doesn't print. I've tried to rearrange the functions, and call the function directly, but it still does not output anything. I seem to be having trouble with something relating to the function bestsol().
import random
import sys
from operator import attrgetter
input = 1
target = 5.5
class Individual:
def __init__(self, constant):
self.fitness = getfitness()
self.constant = constant
def getconstant():
return self.constant
def getresult():
return self.constant * input
def getfitness():
return 10 - abs(target - self.getresult())
def mutate():
if(random.random() > .05):
self.constant + random.random()
def offspring(partner):
return Individual(((self.getconstant() + partner.getconstant())/2))
class Generation(list):
def __init__(self, gensize, fitsize, startinglist=[]):
self.extend(startinglist)
self.bredoff = []
self.gensize = gensize
self.fitsize = fitsize
self.make()
def make():
self = [Individual(random.randint(-10,10)) for x in xrange((self.gensize-len(self)))]
def getfittest():
return heapq.nlargest(self.fitsize,self,key=attrgetter('fitness'))
def getbredoffspring():
for i in self.getfittest():
bredoff.append(i.offspring(self.getfittest[random.randint(0,len(self.getfittest()))]))
return bredoff
class Environment():
def __init__(self, maxgens):
self.l = []
self.b = []
self.maxgens = maxgens
def create():
l = Generation(100,20)
for i in maxgens:
b = l.getbredoffspring()
l = Generation(100,20,b)
def bestsol():
print("e")
print max(l,key=attrgetter('fitness')).fitness()
def main():
sol = Environment(2)
print sol.bestsol
if __name__ == '__main__':
main()
With me being new to python i can't understand even after searching the internet as best i could. Any help will be appreciated.
bestsol is a class method, so when you call it you should use brackets: sol.bestsol() (otherwise, you're print the method object: <bound method Environment.bestsol ...).
Second, when you define a class-method you should declare self as an argument:
def bestsol(self): # <-- here
print("e")
print max(l,key=attrgetter('fitness')).fitness()
Third, when you declare a class that doesn't extend any other class - you should either declare that it inherits from object (old way):
class Environment(object):
or, no brackets at all (new way)
class Environment:
Forth, when you create a class member, say l (you really should use better names btw), whenever you want to use it you should use the self annotation: self.l. If you'll use l it will create a local variable inside the method - and that's probably not what you intended.
There are other problems with the code but I'll let you struggle with it a bit so you can learn :)

Python Classes ( AttributeError: '' object has no attribute '')

Having trouble understanding the problem in my code, new to classes (generally python too, so sorry if I name things wrong). I receive this error:
I think my code is too long winded to include in here, so I made a simplified version to test the concept below.
The question is, how can I create a new self object "self4"? Which would then be available to other functions within the class. Currently I get this error.
AttributeError: 'className' object has no attribute 'self4'
class className(object):
def __init__(self, self1=1,self2=2,self3=3):
self.self1=self1
self.self2=self2
self.self3=self3
def evaluate(self, self5):
print className.func1(self) + className.func2(self)
self.self5=self5
print className.func1(self)
def func1(self):
return self.self1 + self.self5
def func2(self):
self.self4 = self.self1+self.self2+self.self3
return self.self4
filename tester.py
import tester.py
mst=tester.className()
mst.evaluate()
Edit:
Your code works fine!
What is the Problem?
I still think it is better to move self4 into the init!
Original
I think the most logical thing would be to define self4 on init:
class className(object):
def __init__(self, self1=1, self2=2, self3=3):
self.self1 = self1
self.self2 = self2
self.self3 = self3
self.self4 = None
#rest of class
If anyone still has this issue: you get this error when your indentation is goofed.To fix the asked question above, you just have to add a space before the last two functions definitions, that is;
class className(object):
def __init__(self, self1=1,self2=2,self3=3):
self.self1=self1
self.self2=self2
self.self3=self3
def evaluate(self, self5):
print className.func1(self) + className.func2(self)
self.self5=self5
print className.func1(self)
def func1(self):
return self.self1 + self.self5
def func2(self):
self.self4 = self.self1+self.self2+self.self3
return self.self4
just make sure they all have similar indentation, and you are good to go.
You should pass self4 in method.

Why is instance variable not getting recognized

I have the following class in Python.
import os,ConfigParser
class WebPageTestConfigUtils:
def __init__(self, configParser=None, configFilePath=None):
self.configParser = ConfigParser.RawConfigParser()
self.configFilePath = (os.path.join(os.getcwd(),'webPageTestConfig.cfg'))
def initializeConfig(self):
configParser.read(configFilePath)
return configParser
def getConfigValue(self,key):
return configParser.get('WPTConfig', key)
def main():
webPageTestConfigUtils = WebPageTestConfigUtils()
webPageTestConfigUtils.initializeConfig()
webPageTestConfigUtils.getConfigValue('testStatus')
if __name__ =='__main__':
main()
Upon execution . This gives me the error.
NameError: global name 'configParser' is not defined.
Why is python not able to recognize the instance variable here.
~
~
You are defining
...
self.configParser = ConfigParser.RawConfigParser()
...
And accessing using
...
configParser.read(configFilePath)
...
You have to access as self.configParser.
That's expected. In your code, python will not be able to access class members without self. Here is the correct code:
def initializeConfig(self):
self.configParser.read(self.configFilePath)
return self.configParser
def getConfigValue(self,key):
return self.configParser.get('WPTConfig', key)

TypeError: str takes exactly 2 arguments error

I'm having an issue with getting the output I need. I am using a module (called q3.py) with 3 defined classes: Student, Module and Registrations and implementing it into another file with the following details:
#testq3.py
from q3 import *
james = Student('james')
alice = Student('alice')
mary = Student('mary')
agm = Module('agm')
ipp = Module('ipp')
r = Registrations()
r.add(james,agm)
r.add(alice,agm)
r.add(alice,ipp)
mstr = ''
for m in map(str,r.modules(alice)):
mstr = mstr+' '+m
print(alice, 'is doing the following modules:', mstr)
sstr = ''
for s in map(str,r.students(agm)):
sstr = sstr+' '+s
print(agm, 'has the following students:', sstr)
print(r)
And then here is my q3.py file...
class Student:
'Class to define student details'
def __init__(self, name):
self.name = name
def __str__(self, name):
return (self.name)
def __iter__(self, name):
return iter(self.name)
class Module:
'Class to define module codes'
def __init__(self, modules):
self.modules = modules
def __str__(self, modules):
return self.modules
def __iter__(self, modules):
return iter(self.modules)
class Registrations():
'Class telling us what modules students are taking'
def __init__(self):
self.reglist = []
def add(self, students, modules):
self.reglist.append((students, modules))
def students(self, modules):
for x in self.reglist:
if x[1] == modules:
print x[0]
def modules(self, students):
for y in self.reglist:
if y[0] == students:
print y[1]
I keep getting errors such as:
Traceback (most recent call last):
for m in map(str,r.modules(alice)):
File ".....", line 37, in modules
print y[1]
TypeError: __str__() takes exactly 2 arguments (1 given)
So I added in str and also iter as I kept getting argument 2 iteration errors as well. Where am I going wrong? I just want the output to be the same as that in the bottom of testq3.py. Please help?? I'm pretty sure I have plenty of str/iter errors but there must be something else that I'm missing as I'm not getting anywhere near the output I want despite playing around with it for ages. Any help would be appreciated!
Your __str__ methods expect an additional argument but Python doesn't pass that when printing the object.
For example:
def __str__(self, modules):
return self.modules
You need to ensure all __str__ methods have def __str__(self): as signature. For example:
def __str__(self):
return self.modules
Your __str__ and __iter__ methods are taking an unnecessary modules/name argument. Python won't pass this from the str function, and you aren't using it, so just delete it from the argument list of those methods.

Categories