Trying to print from inside a method
I'm still in the process of learning python via a handful of books I bought. One book I am reading just introduced Base Class Methods. I found that I needed more understanding on this concept and wrote a short test program using the Author's code as a vague reference. My question now really isn't Base Class related, but my question stems from my test code so I will just post it as is. ##Test of Super() stuff class First(object): def __init__(self, wamba, nextel): self.wamba = wamba self.nextel = nextel message1 = "This is message 1" print message1 def message22(self): message2 = "This is message 2" print message2 class Second(First): def __init__(self, samba, fextel, sony): super(Second, self).__init__(samba, fextel) self.sony = sony print "This is message 1a" test1 = First(wamba = "Mermaid Man", nextel = "Cell Phone") test2 = Second(samba = "Barnical Boy", fextel = "Hooopla", sony = "Nooo Good!") My question came up when I wanted to print message1 directly and couldn't figure out how to do it. I then added the message22 def thinking that perhaps you couldn't print from constructor methods for some reason. I then added the print line in the message22 def, just out of desperation, and was able to make that work, but is not what I wanted. Here is my copy from my IDEL attempts: This is message 1 This is message 1 This is message 1a >>> test1.message22() This is message 2 >>> test2.message22() This is message 2 >>> print test1.message22.message2 Traceback (most recent call last): File "", line 1, in -toplevel- print test1.message22.message2 AttributeError: 'function' object has no attribute 'message2' >>> print test1.message2 Traceback (most recent call last): File "", line 1, in -toplevel- print test1.message2 AttributeError: 'First' object has no attribute 'message2' >>> print First.message22.message2 Traceback (most recent call last): File "", line 1, in -toplevel- print First.message22.message2 AttributeError: 'function' object has no attribute 'message2' >>> I know this is a very basic question but it's the stupid ones that always get me. - Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to print from inside a method
On Mar 18, 7:32 pm, [EMAIL PROTECTED] (Alex Martelli) wrote: > Here, the message1 and message2 names are LOCAL variables of the > respective methods: each disappear as soon as its method ends. > > If you want to make them into INSTANCE attributes, so they'll stick > around for later, assign to self.message1 and self.message2 instead (and > of course use these composite names too if need be). Ah ha, the nugget of info I was forgetting! Looking back now I can see why the author used the self.whatever, and why my code is not working. When I'm reading along all his code looks find and dandy, makes perfect sense; but soon as I try to do something on my own quickly find that my understanding of how things work is very porous :) > This would be pretty weird, but legal Python. > Weirder and weirder, but still legal Python. This is usually how most of my code turns out :( I'm afraid if I ever learn enough to make a serious program I will be burned at the stake for such un- pythonic practices :P -- http://mail.python.org/mailman/listinfo/python-list
Re: struct.pack returns nothing
On Mar 19, 1:12 am, [EMAIL PROTECTED] wrote:
> If I build a strict with:
>
> import struct
> print struck.pack ('i', 1)
>
> it returns a '\n'.
> What's wrong with it???
> :(
>
> --
> Andrés M.
> -
Looks like you spelled struct wrong in the code :)
--
http://mail.python.org/mailman/listinfo/python-list
TypeError: 'int' object is not callable
I'm trying to test a few different approaches to displaying pages via
Cherrypy and I'm not having much luck. Here is my code so far:
import sys, cherrypy, html
class Root:
@cherrypy.expose
def index(self, pageid = None):
selection = html.Page()
return selection.input()
cherrypy.config.update({'server.socket_port': 2572, 'log.screen':
False})
cherrypy.quickstart(Root())
and here is the html.py file that I import:
class Page:
def input(self,dex=None):
if dex == None:
return 404(dex)
else:
return "Something else?"
def err404(self,whatitis="N/A"):
return """
Sorry the page: """ + str(whatitis) + """ does not exist.
"""
and here is the error I get when trying to run this:
500 Internal Server Error
The server encountered an unexpected condition which prevented it from
fulfilling the request.
Traceback (most recent call last):
File "/home2/awasilenko/lib/python2.4/cherrypy/_cprequest.py", line
342, in respond
cherrypy.response.body = self.handler()
File "/home2/awasilenko/lib/python2.4/cherrypy/_cpdispatch.py", line
15, in __call__
return self.callable(*self.args, **self.kwargs)
File "/home2/awasilenko/webapps/cp/site.py", line 7, in index
return selection.input()
File "/home2/awasilenko/webapps/cp/html.py", line 4, in input
return 404(dex)
TypeError: 'int' object is not callable
I know this isn't a Cherrypy issue since I have made other pages work,
I'm just making a dumb mistake somewhere. My plan is to eventually be
able to pass dex to the input def in the page class so it can display
the right page. Right now I am just trying to make ANY thing show up,
what should happen is since I'm not passing anything everything should
be None and the 404 page should pop up. I would also like to make the
404 page print the page that was requested, I have already coded the
return but have not "connected" it yet, one step at a time...
--
http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: 'int' object is not callable
On Mar 22, 8:59 pm, "Dan Bishop" <[EMAIL PROTECTED]> wrote:
> On Mar 22, 6:54 pm, [EMAIL PROTECTED] wrote:
>
>
>
>
>
> > I'm trying to test a few different approaches to displaying pages via
> > Cherrypy and I'm not having much luck. Here is my code so far:
>
> > import sys, cherrypy, html
>
> > class Root:
> > @cherrypy.expose
> > def index(self, pageid = None):
> > selection = html.Page()
> > return selection.input()
>
> > cherrypy.config.update({'server.socket_port': 2572, 'log.screen':
> > False})
> > cherrypy.quickstart(Root())
>
> > and here is the html.py file that I import:
>
> > class Page:
> > def input(self,dex=None):
> > if dex == None:
> > return 404(dex)
> > else:
> > return "Something else?"
>
> > def err404(self,whatitis="N/A"):
> > return """
> > > />
>
> > Sorry the page: """ + str(whatitis) + """ does not exist.
> >
> > """
>
> > and here is the error I get when trying to run this:
>
> > 500 Internal Server Error
> > The server encountered an unexpected condition which prevented it from
> > fulfilling the request.
>
> > Traceback (most recent call last):
> > File "/home2/awasilenko/lib/python2.4/cherrypy/_cprequest.py", line
> > 342, in respond
> > cherrypy.response.body = self.handler()
> > File "/home2/awasilenko/lib/python2.4/cherrypy/_cpdispatch.py", line
> > 15, in __call__
> > return self.callable(*self.args, **self.kwargs)
> > File "/home2/awasilenko/webapps/cp/site.py", line 7, in index
> > return selection.input()
> > File "/home2/awasilenko/webapps/cp/html.py", line 4, in input
> > return 404(dex)
> > TypeError: 'int' object is not callable
>
> > I know this isn't a Cherrypy issue since I have made other pages work,
> > I'm just making a dumb mistake somewhere. My plan is to eventually be
> > able to pass dex to the input def in the page class so it can display
> > the right page. Right now I am just trying to make ANY thing show up,
> > what should happen is since I'm not passing anything everything should
> > be None and the 404 page should pop up. I would also like to make the
> > 404 page print the page that was requested, I have already coded the
> > return but have not "connected" it yet, one step at a time...
>
> 404 is an integer literal; you can't use it as a function name.- Hide quoted
> text -
>
> - Show quoted text -
I saw that 404 was turning colors in my editor when I used it, that's
why I changed the def name, I just forgot to change it in the input
def also. Here is the working code now:
class Page:
def input(self,dex=None):
if dex == None:
return self.err404(dex)
else:
return "Something else?"
def err404(self,whatitis="N/A"):
return """
Sorry the page: """ + str(whatitis) + """ does not exist.
"""
Now I can work on getting the other stuff working. I can't believe
something that stupid was holding me up, oh well :)
--
http://mail.python.org/mailman/listinfo/python-list
Printing from a text file quirk
I have a html document saved as a text file that I'm trying to load.
Its just the header section so my object is to read all the lines till
I hit the tag, break, then read the rest. I have kinda
achieved what I wanted, but I'm getting a new line where I stopped.
It will become clear once you see the code. So my question is how do
I fix it, or is their an easier way?
Python code:
self.headertxt = open("pages/header.html","r")
*** Irrelevant code omitted ***
headerp1 = ""
for i in range(5):
headerp1 += self.headertxt.readline()
headerp2 = self.headertxt.readline(7)
headerp3 = self.headertxt.readline()
headerp4 = self.headertxt.read()
return headerp1 + headerp2 + headerp3 + pagetitle + headerp4
Here is the textfile im reading:
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";>
http://www.w3.org/1999/xhtml";>
"""
and here is the output:
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";>
http://www.w3.org/1999/xhtml";>
this is a new title
"""
As you can see what I was trying to acheive was the title all on the same line. Help!
--
http://mail.python.org/mailman/listinfo/python-list
Re: Printing from a text file quirk
Humm I think I messed up the code before I pasted it, I am now able to get the left tag on the same line with this: headerp1 = "" for i in range(5): headerp1 += self.headertxt.readline() headerp2 = self.headertxt.readline(7) headerp3 = self.headertxt.readline() headerp4 = self.headertxt.read() return headerp1 + headerp2 + pagetitle + headerp3 + headerp4 output: this is a new title Now all's left is the tag to get on the same line, or a better solution, this seems like a very awkward way to do what I want. -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing from a text file quirk
> Where can I see that? From the python language documentation here: > > http://docs.python.org/lib/lib.html > > you can look up readline() and see: > -- > readline( [size]) > Read one entire line from the file. A trailing newline character is > kept in the string > - > > There is a function called strip() that will strip off all leading and > trailing whitespace on a string, e.g. a newline.- Hide quoted text - > > - Show quoted text - Thank you! Just what I needed :) -- http://mail.python.org/mailman/listinfo/python-list
except clause appears to be being skipped?
I can't figure out this problem Im having, I just can't understand why
it is ignoring the call I put in. First the code (This is a cherrypy
website):
import sys, cherrypy, html
class Root:
@cherrypy.expose
def index(self, pageid = "Index"):
selection = html.Page()
return selection.makeit(dex = pageid)
cherrypy.config.update({'server.socket_port': 2572, 'log.screen':
False})
cherrypy.quickstart(Root())
If you're not familiar with cherrypy, whats going on here is its
pulling a variable from the url and just passing that to my page class
that I created. The url would look like http://nonyaz.com/index?pageid=foo
and pageid would thus be foo.
and here is the class code stored in the html.py file that's causing
me all this grief:
class Page:
#Generic webpage assembler
def __init__(self):
#Open the header txt file for later use
self.headertxt = open("pages/header.html","r")
#self.footertxt = open("pages/footer.html","r")
def makeit(self,dex=""):
pagetitle, htmlbody = self.pager(dex)
return self.headerinsert(pagetitle) + htmlbody
def pager(self,dex):
#Input page filename, Output pagetitle and the HTML output
#Find out if the file requested actually exists
try:
j = dex + ".html"
textfile = open("pages/" + j, "r")
#If not 404' it
except:
self.err404(dex)
#The first line in the .html files is the title, this reads
that one
line
pagetitle = textfile.readline()
#Put the remaining lines of HTML into a var
htmlbody = textfile.read()
#Return the results
return pagetitle,htmlbody
def headerinsert(self,pagetitle):
#Processes the header.html file for use. Input a page title,
outputs
#the compleated header with pagetitle inserted
headerp1 = ""
for i in range(5):
headerp1 += self.headertxt.readline()
headerp2 = self.headertxt.readline(7)
headerp3 = self.headertxt.readline()
headerp4 = self.headertxt.read()
return headerp1 + headerp2 + str.strip(pagetitle) + headerp3 +
headerp4
def err404(self,whatitis="N/A"):
#Page not found error page
return """
Sorry the page """ + str(whatitis) + """ does not
exist.
"""
This code does work when there is a valid page, aka when the try
statement executes with out exception. The the exception is raised
for when there is no file, that's where the problems come in, I want
it just to call the err404 function and return my 404 page, but it
seems to act like its not there and keeps on going, giving me this
error:
Traceback (most recent call last):
File "/home2/awasilenko/lib/python2.4/cherrypy/_cprequest.py", line
342, in respond
cherrypy.response.body = self.handler()
File "/home2/awasilenko/lib/python2.4/cherrypy/_cpdispatch.py", line
15, in __call__
return self.callable(*self.args, **self.kwargs)
File "/home2/awasilenko/webapps/cp/site.py", line 7, in index
return selection.makeit(dex = pageid)
File "/home2/awasilenko/webapps/cp/html.py", line 10, in makeit
pagetitle, htmlbody = self.pager(dex)
File "/home2/awasilenko/webapps/cp/html.py", line 25, in pager
pagetitle = textfile.readline()
UnboundLocalError: local variable 'textfile' referenced before
assignment
I know the except is being executed because I put a break in there for
testing purposes and it did break, but as for why its not pulling up
the 404 function and returning the error page, I have no idea.
--
http://mail.python.org/mailman/listinfo/python-list
Re: except clause appears to be being skipped?
On Mar 23, 10:29 pm, "John Machin" <[EMAIL PROTECTED]> wrote: > It *is* "pulling up the 404 function", which *is* returning your error > page. However all your except clause does is "self.err404(dex)" -- you > ignore the return value, and fall out of the except clause with > textfile undefined, with the expected consequences. Humm I dident think had to put return when I called the 404 becuase the def has a return on the end of that, but now that I think about it more it makes sence. > > I'm not at all familiar with cherrypy, but you probably need to do > either: > errpage = self.err404(dex) > dosomethingwith(errpage, dex) > return > or simply: > return "404 page title", self.err404(dex) > [Actually it would be better style if the err404 method returned a > tuple of (pagetitle, pagebody), then your except clause contains > only: > return self.err404(dex) Both of you're suggestions worked, Change it to return the tuple. > > The main point being to return instead of falling through the bottom > of the except clause. BTW, you should not use a bare except. Be a > little more specific, like except IOError: Suggestion implemented, I figured you could be more specific with exceptions but I must have glazed over that in my book when I read about it. > Looking at the cherrypy docs would seem indicated. Since I'm a noobie python'r (or programmer for that matter) most if not all of my mistkaes are with python and the syntax, there is not much to screw up with Cherrypy itself, but I'm sure I will find a way to screw it up later :) > AFAIK there was a > v1 and a v2 with different naming conventions and there's now a v3 -- > do ensure that you mention which version you are using if you need to > come back with more questions. > > HTH, > John Naming conventions eh? I guess I'm following conventions so far, I havent ran into that problem yet (Knock Knock) Thanks for you're help John, people like you make these newsgroups are an invaluable resource :) -- http://mail.python.org/mailman/listinfo/python-list
