'module' object has no attribute 'scan'.learn python the hard way ex48 - python

I know there're already many people who asked this questions look like this but I really can't find a solution which works for me.
In ex48. I write the "lexicon.py" and nosetests it.but it reports an error:
Traceback (most recent call last):
File "c:\python27\lib\site-packages\nose\case.py", line 197, in runTest
self.test(*self.arg)
File "D:\pyhomework\ex48\skeleton\tests\lexicon_tests.py", line 31, in test_errors
assert_equal(Lexicon.scan("ASDFASDF"),[('errors','ASDFASDF')])
AttributeError: 'module' object has no attribute 'scan'
this is lexicon.py:
class Lexicon(object):
def __init__(self):
self.dic = {'direction':('north','south','east'),
'verb':('go','kill','eat'),
'stop':('the','in','of'),
'noun':('bear','princess'),
'number':('1234','3','91234'),
'error':('ASDFASDF','IAS')}
def scan(self,words):
self.word = words.split()
self.result = []
for item in self.word:
for key,value in self.dic.items():
if item in value:
self.result.append((key,item))
return self.result
this is lexicon_tests.py
from nose.tools import *
from ex48 import Lexicon
def test_direction():
assert_equal(Lexicon.scan("north"),[('direction','north')])
result = Lexicon.scan("north south east")
assert_equal(result,[('direction','north'),('direction','south'),('direction','east')])
def test_verbs():
assert_equal(Lexicon.scan("go"),[('verb','go')])
result = Lexicon.scan("go kill eat")
assert_equal(result,[('verb','go'),('verb','kill'),('verb','eat')])
def test_stops():
assert_equal(Lexicon.scan("the"),[('stop','the')])
result = Lexicon.scan("the in of")
assert_equal(result,[('stop','the'),('stop','in'),('stop','of')])
def test_nouns():
assert_equal(Lexicon.scan("bear"),[('noun','bear')])
result = Lexicon.scan("bear princess")
assert_equal(result,[('noun','bear'),('noun','princess')])
def test_numbers():
assert_equal(Lexicon.scan("1234"),[('number','1234')])
result = Lexicon.scan("3 91234")
assert_equal(result,[('number','3'),('number','91234')])
def test_errors():
assert_equal(Lexicon.scan("ASDFASDF"),[('errors','ASDFASDF')])
result = Lexicon.scan("bear IAS princess")
assert_equal(result,[('noun','bear')('error','IAS')('noun','princess')])
this is the skeleton:
-bin
-docs
-ex48 (-__init__.py -Lexicon.py)
-tests (-__init__.py -lexicon_tests.py)
-setup
I have tried several ways but still get the same error.
thank you for any advice.

When you write from ex48 import Lexicon what is imported is the Lexicon.py file as a python module. Yet, this module contains a Lexicon class, which contains the method you want to use.
To get rid of your error, try this import statement : from ex48.lexicon import Lexicon this way you will use the Lexicon object that is defined in the lexicon.py file.

from ex48 import Lexicon
So you imported the module lexicon.py.
In your module lexicon.py you have a class Lexicon.
So to call methods of the class Lexicon you have to use notation
Lexicon.Lexicon.method()

Related

NameError creating instance of imported class

I have a subclassed Course class as follows:
# course.py
class Course:
"""Represent a single Course"""
kind = 'Gen Ed'
def __init__(self, name, number) :
self._name = name # 'private' instance variable\
self._number = number
self.__display()
def display(self):
print(self.kind,"Course:" , self._name, self._number, sep=" ")
__display = display # private copy
class CSCourse(Course):
"""Represent a single CS Course"""
kind = 'CS' # class variable shared by all CSCourses
def __init__(self, name, number, language, numberOfPrograms):
Course.__init__(self, name, number)
self._language = language
self._numberOfPrograms = numberOfPrograms
def display(self):
Course.display(self)
print('Language', self._language,
'Number Of programs:', self._numberOfPrograms, sep = ' ')
I import the module as follows:
>>>from course import *
This does not throw any exception, but then when I issue the following to call the constructor, I get the error below?
>>> cs360=CSCourse("Special Topics", 360, "python", 21)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'CSCourse' is not defined
What am I doing wrong please? I did also try to see what methods are available in the classes imported. It seems nothing is being imported!
>>> import inspect
>>> inspect.getmembers(Course, lambda a:not(inspect.isroutine(a)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Course' is not defined
>>> inspect.getmembers(CSCourse, lambda a:not(inspect.isroutine(a)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'CSCourse' is not defined
For anyone else having this problem, check if you have circular imports (in file a.py from b import * and in file b.py from a import *). Python doesn't seem to raise an exception when that happens, but the import doesn't work. Restructuring the code to remove the circular import fixed the problem for me.

Attribute Error in python. Object has no attribute

This code is part of a bigger program that uses the google Sheets API to get data from a cloud database (not really relevant, but a bit of context never hurt!)
I have this black of code in one python file named 'oop.py'
class SetupClassroom:
def __init__(self, arraynumber='undefined', tkroot='undefined'):
self.arraynumber = arraynumber
self.tkroot = tkroot
def setarraynumber(self, number):
from GUI_Stage_3 import showclassroom
self.arraynumber = number
print ('set array number:', number)
showclassroom()
def settkroot(self, tkrootinput):
self.tkroot = tkrootinput
self.tkroot has been assigned by another part of the code. This bit works, as I have already tested that it is being assigned, however, when I call 'self.tkroot' in another another file like this
def showclassroom():
from oop import SetupClassroom
username = current_user.username
classnumber = getnumberofuserclassrooms(username)
if SetupClassroom.arraynumber > classnumber:
errorwindow('you are not enrolled in that many classrooms!')
else:
classtoget = SetupClassroom.arraynumber
print('classtoget:', classtoget)
root = SetupClassroom.tkroot
name_label = Label(root, text=classtoget)
getclassroom(username, classtoget)
SetupClassroom = SetupClassroom
I get this error
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/GUI_Stage2_better.py", line 176, in <lambda>
l0 = ttk.Button(teacher_root, text=button0text, command=lambda: (SetupClassroom.setarraynumber(SetupClassroom, number=button0text), SetupClassroom.settkroot(SetupClassroom, 'teacher_root')))
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/oop.py", line 99, in setarraynumber
showclassroom()
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/GUI_Stage_3.py", line 29, in showclassroom
root = SetupClassroom.tkroot
AttributeError: type object 'SetupClassroom' has no attribute 'tkroot'
I tried setting it up in the python console and it worked, so I have no idea what the problem is.
If anyone could help, it would be very much appreciated
Thanks!
John
You should create an instance of class, it will create the attribute in __init__, self.tkroot is the attribute of instance not class:
setupClassroom = SetupClassroom()
print(setupClassroom.tkroot)
Hope that will help you.

Python - Creating an instance of a module, getting an error

I am creating a universal text field that can be used in many python turtle projects. I am trying to create an instance of it but I get this error:
>>> import TextField
>>> tf = TextField('None', False)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tf = TextField('None', False)
TypeError: 'module' object is not callable
>>>
What in a module causes this type of error? I completely wrote this module and I'm getting an error creating an instance of it :( ... What do I need in this module to make it 'callable'? I have tried adding a def __call__(self): but that doesn't affect the problem at all, nor create any errors.
Here is the beginning of the script where the problem is most likely happening:
# Created by SUPERMECHM500 # repl.it
# Edited by cdlane # stackoverflow.com
class TextField:
TextFieldBorderColor = '#0019fc'
TextFieldBGColor = '#000000'
TextFieldTextColor = '#ffffff'
ShiftedDigits = {
'1':'!',
'2':'#',
'3':'#',
'4':'$',
'5':'%',
'6':'^',
'7':'&',
'8':'*',
'9':'(',
'0':')'
}
def __init__(self, command, CanBeEmpty): # Ex. textField = TextField('Execute()', True)
self.CmdOnEnter = command
self.turtle = Turtle()
self.CanBeEmpty = CanBeEmpty
self.turtle.speed('fastest')
self.inp = []
self.FullOutput = ""
self.TextSeparation = 7
self.s = self.TextSeparation
self.key_shiftL = False
......
The module is not the class. If your class TextField is in a module called TextField, then it is referred to as TextField.TextField.
Or change your import to
from TextField import TextField

Python Crash Course, Testing Your Code example

This is to test the class; however, I am getting an error and I do not know how to fix it.
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'"""
def test_first_last_name(self):
"""Do names like 'Mark James' work?"""
formatted_name = get_formatted_name('mark','James')
self.assertEqual(formatted_name,'Mark James')
unittest.main()
Here's the class that is being tested.
def get_formatted_name(first, last):
"""This is where the name is formatted correctly"""
full_name = first + " " + last
return full_name.title()
The error I am getting is this:
/Desktop/python_work/test_name_function.py", line 1, in <module>
import unittest
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/__init__.py", line 58, in <module>
from .result import TestResult
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/result.py", line 5, in <module>
import traceback
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/traceback.py", line 3, in <module>
import linecache
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/linecache.py", line 10, in <module>
import tokenize
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tokenize.py", line 96, in <module>
class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
AttributeError: 'module' object has no attribute 'namedtuple'
Anyone have a clue?
I believe you need to add if 'name' == 'main':
unittest.main() to your code.
The below code should fix the error -
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'"""
def test_first_last_name(self):
"""Do names like 'Mark James' work?"""
formatted_name = get_formatted_name('mark','James')
self.assertEqual(formatted_name,'Mark James')
if '__name__' == '__main__':
unittest.main()

Python unittesting initiate values

Sorry if this question is stupid. I created an unittest class which needs to take given inputs and outputs from outside. Thus, I guess these values should be initiated. However, I met some errors in the following code:
CODE:
import unittest
from StringIO import StringIO
##########Inputs and outputs from outside#######
a=[1,2]
b=[2,3]
out=[3,4]
####################################
def func1(a,b):
return a+b
class MyTestCase(unittest.TestCase):
def __init__(self,a,b,out):
self.a=a
self.b=b
self.out=out
def testMsed(self):
for i in range(self.tot_iter):
print i
fun = func1(self.a[i],self.b[i])
value = self.out[i]
testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("func1",i,value,fun)
self.assertEqual(round(fun,3),round(value,3),testFailureMessage)
if __name__ == '__main__':
f = MyTestCase(a,b,out)
from pprint import pprint
stream = StringIO()
runner = unittest.TextTestRunner(stream=stream, verbosity=2)
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
print 'Tests run', result.testsRun
However, I got the following error
Traceback (most recent call last):
File "C:testing.py", line 33, in <module>
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
File "C:\Python27\lib\unittest\loader.py", line 310, in makeSuite
return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
File "C:\Python27\lib\unittest\loader.py", line 50, in loadTestsFromTestCase
if issubclass(testCaseClass, suite.TestSuite):
TypeError: issubclass() arg 1 must be a class
Can anyone give me some suggestions? Thanks!
The root of the problem is this line,
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
unittest.makeSuite expects a class, not an instance of a class. So just MyTestCase, not MyTestCase(a, b, out). This means that you can't pass parameters to your test case in the manner you are attempting to. You should probably move the code from init to a setUp function. Either access a, b, and out as globals inside setUp or take a look at this link for information regarding passing parameters to a unit test.
By the way, here is the source file within python where the problem originated. Might be informative to read.

Categories

Resources