Keep getting "function has no attribute" error - python-2.7

This is the error I get:
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensio
ns\Microsoft\Python Tools for Visual Studio\2.0\visualstudio_py_util.py", line 7
6, in exec_file
exec(code_obj, global_variables)
File "c:\users\tim\documents\visual studio 2013\Projects\Text Game\Text Game\T
ext_Game.py", line 57, in <module>
a_game.play()
File "c:\users\tim\documents\visual studio 2013\Projects\Text Game\Text Game\T
ext_Game.py", line 12, in play
next_scene_name = current_scene.enter() #prints scene's info
AttributeError: 'function' object has no attribute 'enter'
This is my code (written in Python 2.7):
from sys import exit
from random import randint
class Engine(object):
def __init__(self,scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.start_scenes
while True: #this is always running until Death, this pulls next scene up
print "\n--------"
next_scene_name = current_scene.enter() #prints scene's info
current_scene = self.scene_map.next_scene() #this has to take result of scene to play next scene
class Player(object): #once rest of code works we implement more moplicated player traits.
pass
class Scene(object):
def enter(self):
print "Scene info"
exit(1)
class Death(Scene):
quips = [
"Wow. Much Death, so sad. Wow.",
"Hah you suck at this!",
"Try Again!",
]
def enter(self):
print Death.quips[randint(0, len(self.quips)-1)]
exit(1)
class Room1(Scene):
def enter(self):
print "Scene Intro"
choice_i = raw_input("\n >")
choice=choice_i.lower()
if choice == "left" or choice == "l":
return "room10"
elif choice == "right" or choice == "r":
return "room2"
else:
print "Choose left or right (l/r)"
return "Room1" #Engine or Map will take the room names to restart a room (or death or finish to end game)
class Map(object):
scenes = {"room1": Room1(), "death": Death()}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def start_scenes(self):
return self.next_scene(self.start_scene)
a_map = Map("Room1")
a_game = Engine(a_map)
a_game.play()
--------
Im a beginner and classes confuse me relatively easily. Im trying to make a text based game (as you porbably noticed its in a lesson from learnpythonthehardway) I want to add a lot of extra functionality past going through rooms but I cant seem to get the rooms working.
Sorry for the info dump but if you could help that would be amazing
.

You forgot to actually call the method.
def play(self):
current_scene = self.scene_map.start_scenes()
...

Related

tkSimpleDialog pycharm

I am coding for a school project and was trying to use tkinter in my code, but it kept coming up with an error. I am using a mac laptop and the pycharm interface
Traceback (most recent call last):
File "/Users/-----/Desktop/python/Tkinter turtle obstacle.py", line 20, in <module>
color1()#does it automatically
File "/Users/-----/Desktop/python/Tkinter turtle obstacle.py", line 8, in color1
ac1 = Sd("Color Selector", 'Enter the color of the turtle')
TypeError: 'module' object is not callable
Here is my code, its just a simple project to test it before i delve into the final one but I cannot get it to work, can someone please tell me what is wrong with it:
import turtle # 1. import the modules
import random
import Tkinter as tk
import tkSimpleDialog as Sd
def color1():
ac1 = Sd("Color Selector", 'Enter the color of the turtle')
steve.color(ac1)
print(5)
def color2():
ac2 = Sd("Color Selector", 'Enter the color of the obstacle')
sam.color(ac2)
root = tk.Tk()
wn = turtle.Screen() # 2. Create a screen
wn.bgcolor('white')
steve = turtle.Turtle() # 3. Create two turtles
sam = turtle.Turtle()
color1()#does it automatically
color2()
red = tk.Button(root, text = "Enter String", command = color1)#this puts it on a button click
blue = tk.Button(root, text = "Enter String", command = color2)
red.grid(row=0,column=0)
blue.grid(row=1,column=0)
steve.shape('turtle')
sam.shape('circle')
steve.speed(1)
sam.speed(1)
steve.pensize(5)
sam.pensize(25)
sam.penup()
sam.pendown()
steve.penup()
steve.goto(-300,0)
sam.goto(0,0)
b = True
while b is True:
steve.pendown()
steve.forward(20)
if steve.xcor() == sam.xcor() -40:
steve.left(90)
steve.forward(30)
steve.right(90)
if steve.xcor() == sam.xcor() +40:
steve.right(90)
steve.forward(30)
steve.left(90)
if steve.xcor() == 200:
steve.write('Obstacle Avoided', font=('Arial', 20, "bold"))
break
wn.exitonclick()
tkSimpleDialog is a module, not a Class.
You probably want to create an instance of a Class in this module.
Look for the Classes in the module and use the correct Class to create the instance.

AttributeError: 'NoneType' object has no attribute 'find' with python 2.7 using BeautifulSoup

I just began python crawling and have tried to crawl web text for a month.
I tried this code with python 2.7.13 and it worked well before.
class IEEECrawler:
def __init__(self):
self.baseUrl = "http://ieeexplore.ieee.org"
self.targetUrl = "http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?reload=true&filter%3DAND%28p_IS_Number%3A4359286%29&rowsPerPage=100&pageNumber=1&resultAction=REFINE&resultAction=ROWS_PER_PAGE&isnumber=4359286#1.html"
self.soup = BeautifulSoup(urllib.urlopen(self.targetUrl).read(), "lxml")
self.doc_list = self.soup.find_all('div', {'class': "txt"})
self.subUrl = []
def crawlOriginalPage(self):
file = open("./result.txt", "w")
for doc in self.doc_list:
head = doc.find("h3")
author_list = ''
for author in doc.find_all("div", {'class':"authors"}):
for tt in author.find_all('span', {'id':"preferredName"}):
author_list += tt['data-author-name'] + ";"
author_list = author_list[:-1]
file.write(head.find("span").text + ';')
file.write(author_list.strip() + ';')
file.write(self.baseUrl+head.find('a')['href']+ ';')
file.write(doc.find("div", {'class': "hide abstract RevealContent"}).find("p").text.replace('View full abstract'+'»'.decode('utf-8'),'').strip()+ '\n')
file.close()
print 'finish'
However, today I ran this code again, I doesn't work with this error masseges. I can't figure out what code should be fixed.
Traceback (most recent call last):
File "/Users/user/Downloads/ieee_fin/ieee.py", line 35, in <module>
crawler.crawlOriginalPage()
File "/Users/user/Downloads/ieee_fin/ieee.py", line 29, in crawlOriginalPage
file.write(doc.find("div", {'class': "hide abstract RevealContent"}).find("p").text.replace('View full abstract'+'»'.decode('utf-8'),'').strip()+ '\n')
AttributeError: 'NoneType' object has no attribute 'find'
The error shows you the line:
file.write(doc.find("div", {'class': "hide abstract RevealContent"}).find("p").text.replace('View full abstract'+'»'.decode('utf-8'),'').strip()+ '\n')
Just look for the method find (there are 2) and check to see what comes before it.
Maybe this is bad:
doc.find(...)
Which would mean that doc was type NoneType, which would mean that doc was None.
Or maybe this is bad:
doc.find("div", {'class': "hide abstract RevealContent"}).find("p")
Which would mean that doc.find(...class...) is returning None. Possibly because it couldn't find any.
Bottom line, you probably either need to put a try...except wrapper around that code, or break it up a little and start checking for None.

PyQt - Getting an error when trying to use emit

I am trying to use emit for the first time in PyQt. I have done a lot of reading and googling and I was sure I had this correct but I keep getting the errors shown below. Can anyone shed some light on what I am doing wrong.
def checkRiskDescription(obj,form):
complete = True
if str(form.txtTitle.text()) == "":
complete = False
if len(str(form.txtOverview.toPlainText())) < 50:
complete = False
bar = form.tabRiskMain.tabBar()
if complete:
#Change Risk Description tab to Green
bar.setTabTextColor(0,QtGui.QColor(38, 169, 11, 255))
form.btnSave.enabeld = True
else:
#Change risk Description tab to Red
bar.setTabTextColor(0,QtGui.QColor(255, 0, 0, 255))
form.btnSave.enabled = False
QtGui.QWidget.emit(QtCore.SIGNAL("tabsUpdated"))
Here is the error
File "D:\Development\python\PIF2\PIF\risk\risk.py", line 360, in checkRiskDescription
QtGui.QWidget.emit(QtCore.SIGNAL("tabsUpdated"))
TypeError: QObject.emit(SIGNAL(), ...): first argument of unbound method must have type 'QObject'
I normally just define the signal like this
tabsUpdated = Qt.pyqtSignal()
then fire it via
self.tabsUpdated.emit()
E.g
from PyQt4 import Qt
class SomeClass(Qt.QObject):
tabsUpdated = Qt.pyqtSignal()
def __init__(self):
Qt.QObject.__init__(self)
def something(self):
# bla bla loads of nice magic code bla bla
self.tabsUpdated.emit()
of course the signal could be defined globally in your python file.

Python List NoneType Error

I'm having an issue with an OpenCourseWare project I'm trying to implement. I'm creating a hangman game and everything seems to be okay until I attempt to run the actual function for playing the game.
I'm receiving the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "Game of Hangman/hangman.py", line 118, in play_hangman
print(print_guessed())
File "Game of Hangman/hangman.py", line 92, in print_guessed
if letter in letters_guessed == True:
TypeError: argument of type 'NoneType' is not iterable
I can't seem to understand why the list is evaluating to a NoneType even though it is declared as an empty list. I've used the console to attempt to find the answer and says the type is NoneType. Could someone help me please? I've provided the code as a reference.
# Name:
# Section:
# 6.189 Project 1: Hangman template
# hangman_template.py
# Import statements: DO NOT delete these! DO NOT write code above this!
from random import randrange
from string import *
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
# Import hangman words
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = split(line)
print " ", len(wordlist), "words loaded."
print 'Enter play_hangman() to play a game of hangman!'
return wordlist
# actually load the dictionary of words and point to it with
# the words_dict variable so that it can be accessed from anywhere
# in the program
words_dict = load_words()
# Run get_word() within your program to generate a random secret word
# by using a line like this within your program:
# secret_word = get_word()
def get_word():
"""
Returns a random word from the word list
"""
word=words_dict[randrange(0,len(words_dict))]
return word
# end of helper code
# -----------------------------------
# CONSTANTS
MAX_GUESSES = 6
# GLOBAL VARIABLES
secret_word = get_word()
letters_guessed = []
# From part 3b:
def word_guessed():
'''
Returns True if the player has successfully guessed the word,
and False otherwise.
'''
global secret_word
global letters_guessed
wordGuessed = False
####### YOUR CODE HERE ######
for letter in secret_word:
if letter in letters_guessed:
wordGuessed = True
else:
wordGuessed = False
break
return wordGuessed
def print_guessed():
'''
Prints out the characters you have guessed in the secret word so far
'''
global secret_word
global letters_guessed
printedWord = []
####### YOUR CODE HERE ######
for letter in secret_word:
if letter in letters_guessed:
printedWord.append(letter)
else:
printedWord.append("-")
return printedWord
def play_hangman():
# Actually play the hangman game
global secret_word
global letters_guessed
# Put the mistakes_made variable here, since you'll only use it in this function
mistakes_made = 0
# Update secret_word. Don't uncomment this line until you get to Step 8.
secret_word = get_word()
####### YOUR CODE HERE ######
while mistakes_made < MAX_GUESSES or word_guessed() == False:
print("WORD:")
userGuess = raw_input("What is your guess?\n").lower()
if userGuess in secret_word:
letters_guessed = letters_guessed.append(userGuess)
else:
letters_guessed = letters_guessed.append(userGuess)
mistakes_made += 1
print(print_guessed())
if word_guessed() == False:
print("Sorry but you've run out of guesses...")
else:
print("You've correctly guessed the secret word!")
print("Secret Word: " + secret_word)
Just as a disclaimer, this isn't an assignment in the sense I'm not enrolled in school. I'm just a guy trying to get back in to programming and found some assignments to play with.
Looks like I've found my answer. The problem appeared to be with the assignment I was doing with the letters_guessed variable.
Instead of doing:
letters_guessed = letters_guessed.append(userGuess)
I should have done:
letters_guessed.append(userGuess)

Why can't an object use a method as an attribute in the Python package ComplexNetworkSim?

I'm trying to use the Python package ComplexNetworkSim, which inherits from networkx and SimPy, to simulate an agent-based model of how messages propagate within networks.
Here is my code:
from ComplexNetworkSim import NetworkSimulation, NetworkAgent, Sim
import networkx as nx
#define constants for our example of states
NO_MESSAGE = 0
MESSAGE = 1
class Message(object):
def __init__(self,topic_pref):
self.relevance = topic_pref
class myAgent(NetworkAgent):
def __init__(self, state, initialiser):
NetworkAgent.__init__(self, state, initialiser)
self.state = MESSAGE
self.topic_pref = 0.5
def Run(self):
while True:
if self.state == MESSAGE:
self.message = self.Message(topic_pref, self, TIMESTEP)
yield Sim.hold, self, NetworkAgent.TIMESTEP_DEFAULT
elif self.state == NO_MESSAGE:
yield Sim.hold, self, NetworkAgent.TIMESTEP_DEFAULT
# Network and initial states of agents
nodes = 30
G = nx.scale_free_graph(nodes)
states = [MESSAGE for n in G.nodes()]
# Simulation constants
MAX_SIMULATION_TIME = 25.0
TRIALS = 2
def main():
directory = 'test' #output directory
# run simulation with parameters
# - complex network structure
# - initial state list
# - agent behaviour class
# - output directory
# - maximum simulation time
# - number of trials
simulation = NetworkSimulation(G,
states,
myAgent,
directory,
MAX_SIMULATION_TIME,
TRIALS)
simulation.runSimulation()
if __name__ == '__main__':
main()
(There may be other problems downstream with this code and it is not fully tested.)
My problem is that the myAgent object is not properly calling the method Run as an attribute. Specifically, this is the error message that I get when I try to run the above code:
Starting simulations...
---Trial 0 ---
set up agents...
Traceback (most recent call last):
File "simmessage.py", line 55, in <module>
main()
File "simmessage.py", line 52, in main
simulation.runSimulation()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/ComplexNetworkSim-0.1.2-py2.7.egg/ComplexNetworkSim/simulation.py", line 71, in runSimulation
self.runTrial(i)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/ComplexNetworkSim-0.1.2-py2.7.egg/ComplexNetworkSim/simulation.py", line 88, in runTrial
self.activate(agent, agent.Run())
AttributeError: 'myAgent' object has no attribute 'Run'
Does anybody know why this is? I can't figure how my code differs substantially from the example in ComplexNetworkSim.
I've run your code on my machine and there the Run method gets called.
My best guess is what Paulo Scardine wrote, but since i can't reproduce the problem i can't actually debug it.