Re: [Tutor] Floating point exercise 3 from Learn python the hard way
On Tue, Jun 14, 2011 at 12:27 AM, Alan Gauld wrote: > > I can understand why at line 5 I use floating point. 6,75 is more >> precise than saying 7. >> > > Exactly, no problem with line 5 (except the odd comment about 6.83) The comment on line 5 was a mistake. > > But I can't understand at line 2 and 3. I mean it makes no difference >> for me. Saying 30 or 30.0 is the same thing. >> As well as saying 97 or 97.0. >> > > Precisely, thats why I asked the question. > > As a beginner at line 2 and 3 I see no point of using floating numbers except the fact to serve as an example that if I have a floating point number it affects the rest of the expression evaluation. So, should I keep them or not?It's unclear to me and sadly the author of the book doesn't provide the solutions to the exercises. The only way I can verify myself is using this list. Regards, amt. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Floating point exercise 3 from Learn python the hard way
I too am working through Learn Python the Hard Way. On Tuesday 14 June 2011 14:20:43 amt wrote: > sadly the author of the > book doesn't provide the solutions to the exercises. He gives the answers to the questions in the main block of the chapter, just not for the extra credit questions. I have taken the attitude that if I can't do any of the extra credit questions, having successfully done the questions in the chapter, I pass on and will come back to them when I know a bit more. Lisi ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Floating point exercise 3 from Learn python the hard way
On 14 June 2011 15:20, amt <0101...@gmail.com> wrote: >>> But I can't understand at line 2 and 3. I mean it makes no difference >>> for me. Saying 30 or 30.0 is the same thing. >>> As well as saying 97 or 97.0. >> >> Precisely, thats why I asked the question. > > As a beginner at line 2 and 3 I see no point of using floating numbers > except the fact to serve as an example that if I have a floating point > number it affects the rest of the expression evaluation. Correct, 2 and 3 do not need floating point arithmetic. > So, should I keep them or not?It's unclear to me and sadly the author of the > book doesn't provide the solutions to the exercises. The only way I can > verify myself is using this list. If you tell Python to divide 2 integers (whole numbers) by default it will use integer arithmetic. So in your calculation on line 5 you get a result of 7 as Python does not switch to floating point arithmetic. You can ask Python to use floating point arithmetic a couple of ways. For example if you want 2 divided by 3 you can tell Python to use floating point arithmetic by: --1-- >>> float(2) / 3 0. >>> float(20) / 7 2.857142857142857 --2-- >>> 2.0 / 3 0. >>> 20.0 / 7 2.857142857142857 What happens here is that Python on one side of the division has a floating point number. This will force it to use floating point arithmetic instead of integer. Generally the second form is used and the first is for demonstration purpose only. >>> 2 / 3 0 >>> 20 / 7 2 Here we have 2 integers and therefor Python uses integer arithmetic and gives 0 and 2 as result. This is because the results of the division can not be stored as an integer so everything after the decimal place gets cut off. In Python 3 this has been changed that by default it will do floating point arithmetic. You can also get this in Python 2 by importing division from __future__. The Python tutorial [1] on floating point arithmetic will give you much more info on floating point arithmatic in Python. Greets Sander [1] http://docs.python.org/tutorial/floatingpoint.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Floating point exercise 3 from Learn python the hard way
Everything is clear now. Thank you for your replies. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] trying to translate and ebcidic file
I am looking for a way to translate and ebcidic file to ascii. Is there a pre-existing library for this, or do I need to do this from scratch? If from scratch and ideas on where to start? thanks Craig Prinn Document Solutions Manager Office Phone 919-767-6640 Cell Phone410-320-9962 Fax 410-243-0973 3600 Clipper Mill Road Suite 404 Baltimore, MD 21211 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Break stament issue
Hello members! I'm doing a script that needs to loop to get some information, in order to do that I'm using modules from OGR and Mapnik. These to get data from shapefiles, but some of the files have 0 elements, I wrote a line to validate it, but it hasn't worked, so I added a break to keep working. When I run the scipt I got the next error: Traceback (most recent call last): File "", line 1, in import mapnik_punto_sin_duda File "C:\Python26\mapnik_punto_sin_duda.py", line 23 break ^ IndentationError: unexpected indent But I've read about this stamentet's use and I don't understand the reason I'm failing, the complete script is: import mapnik import os,fnmatch from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer from osgeo import ogr,gdal,osr #Registra todos los drivers de GDAL file_list = [] #Crear variable para buscar dentro de carpetas en el sistema folders = None #Se asigna el directorio raiz donde se van buscar los archivos, se hace un recorrido en la raiz for root, folders, files in os.walk( "c:\\" ): #Agregar a la lista los elementos que traiga os.path.join, los archivos que terminen en extension .shp for filename in fnmatch.filter(files, '*.shp'): file_list.append(os.path.join(root, filename)) #Recorrer la lista que se creo for row, filepath in enumerate(file_list, start=1): #Dividir la ruta en dos: directorio y nombre de archivo dir(LineSymbolizer().stroke) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp break else: layer = shapeData.GetLayer() defn = layer.GetLayerDefn() geo = defn.GetGeomType() (ruta, filename) = os.path.split(filepath) archivo = os.path.splitext(filename) i = archivo[0]+'.png' m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") m.background = mapnik.Color('#EBEBEB') s = mapnik.Style() r=mapnik.Rule() if geo == 3: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." elif geo == 2: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." elif geo == 1: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) blue = mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) blue.allow_overlap = True s=mapnik.Style() r=mapnik.Rule() r.symbols.append(blue) s.rules.append(r) #s.rules.append(blue) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." else: print "Algo fallo y no entro a ninguna de las geometrias" print "Listo" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trying to translate and ebcidic file
On 14-Jun-11 11:40, Prinn, Craig wrote: I am looking for a way to translate and ebcidic file to ascii. Is there a pre-existing library for this, or do I need to do this from scratch? If from scratch and ideas on where to start? Bear in mind that there's no 100% straight-across translation, because ASCII and EBCDIC each has characters that the other lacks. However, to translate the character codes they share in common, you could do something as simple as using the translation table functionality built in to the string class in Python, setting up a table to convert between one and the other. of course, if you are on a Unix-like system, there's already a command for that, to convert a file "E" from EBCDIC to a file "A" in ASCII: $ dd if=E of=A conv=ascii or the other way: $ dd if=A of=E conv=ebcdic -- Steve Willoughby / st...@alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Break stament issue
-- Forwarded message -- From: Susana Iraiis Delgado Rodriguez Date: 2011/6/14 Subject: Break stament issue To: tutor@python.org Hello members! I'm doing a script that needs to loop to get some information, in order to do that I'm using modules from OGR and Mapnik. These to get data from shapefiles, but some of the files have 0 elements, I wrote a line to validate it, but it hasn't worked, so I added a break to keep working. When I run the scipt I got the next error: Traceback (most recent call last): File "", line 1, in import mapnik_punto_sin_duda File "C:\Python26\mapnik_punto_sin_duda.py", line 23 break ^ IndentationError: unexpected indent But I've read about this stamentet's use and I don't understand the reason I'm failing, the complete script is: import mapnik import os,fnmatch from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer from osgeo import ogr,gdal,osr #Registra todos los drivers de GDAL file_list = [] #Crear variable para buscar dentro de carpetas en el sistema folders = None #Se asigna el directorio raiz donde se van buscar los archivos, se hace un recorrido en la raiz for root, folders, files in os.walk( "c:\\" ): #Agregar a la lista los elementos que traiga os.path.join, los archivos que terminen en extension .shp for filename in fnmatch.filter(files, '*.shp'): file_list.append(os.path.join(root, filename)) #Recorrer la lista que se creo for row, filepath in enumerate(file_list, start=1): #Dividir la ruta en dos: directorio y nombre de archivo dir(LineSymbolizer().stroke) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp break else: layer = shapeData.GetLayer() defn = layer.GetLayerDefn() geo = defn.GetGeomType() (ruta, filename) = os.path.split(filepath) archivo = os.path.splitext(filename) i = archivo[0]+'.png' m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") m.background = mapnik.Color('#EBEBEB') s = mapnik.Style() r=mapnik.Rule() if geo == 3: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." elif geo == 2: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." elif geo == 1: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) blue = mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) blue.allow_overlap = True s=mapnik.Style() r=mapnik.Rule() r.symbols.append(blue) s.rules.append(r) #s.rules.append(blue) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." else: print "Algo fallo y no entro a ninguna de las geometrias" print "Listo" ___ Tutor maillist - Tutor@python.org To unsubscribe
Re: [Tutor] trying to translate and ebcidic file
On Tue, Jun 14, 2011 at 2:40 PM, Prinn, Craig wrote: > I am looking for a way to translate and ebcidic file to ascii. Is there a > pre-existing library for this, or do I need to do this from scratch? If from > scratch and ideas on where to start? If the file is essentially a text file, I would read the contents in, decode the resulting bytes to a unicode string, then encode the unicode string to the encoding of your choice (ascii, utf-8, etc). You'll also need to know which variant of EBCDIC you're dealing with. I'm assuming CCSID 500. Something like this: input_file = open('my_ebcidic_file', 'rb') ebcidic_bytes = input_file.read() unicode_str = ebcidic_bytes.decode('cp500') ascii_str = unicode_str.encode('ascii') You can do it in less steps, but that should give you something to start with. Jerry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Break stament issue
On Tue, Jun 14, 2011 at 2:59 PM, Susana Iraiis Delgado Rodriguez < susana.delgad...@utzmg.edu.mx> wrote: > Hello members! > > I'm doing a script that needs to loop to get some information, in order to > do that I'm using modules from OGR and Mapnik. These to get data from > shapefiles, but some of the files have 0 elements, I wrote a line to > validate it, but it hasn't worked, so I added a break to keep working. When > I run the scipt I got the next error: > Traceback (most recent call last): > File "", line 1, in > import mapnik_punto_sin_duda > File "C:\Python26\mapnik_punto_sin_duda.py", line 23 > break >^ > IndentationError: unexpected indent > > But I've read about this stamentet's use and I don't understand the reason > I'm failing, the complete script is: > import mapnik > import os,fnmatch > from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer > from osgeo import ogr,gdal,osr > > #Registra todos los drivers de GDAL > file_list = [] > #Crear variable para buscar dentro de carpetas en el sistema > folders = None > #Se asigna el directorio raiz donde se van buscar los archivos, se hace un > recorrido en la raiz > for root, folders, files in os.walk( "c:\\" ): > #Agregar a la lista los elementos que traiga os.path.join, los > archivos que terminen en extension .shp > for filename in fnmatch.filter(files, '*.shp'): > file_list.append(os.path.join(root, filename)) > #Recorrer la lista que se creo > for row, filepath in enumerate(file_list, start=1): > #Dividir la ruta en dos: directorio y nombre de archivo > dir(LineSymbolizer().stroke) > shapeData = ogr.Open(filepath) > shp = 'Error al abrir el archivo' +filepath > if shapeData is None: > print shp > break > else: > layer = shapeData.GetLayer() > defn = layer.GetLayerDefn() > geo = defn.GetGeomType() > (ruta, filename) = os.path.split(filepath) > archivo = os.path.splitext(filename) > i = archivo[0]+'.png' > > m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") > m.background = mapnik.Color('#EBEBEB') > s = mapnik.Style() > r=mapnik.Rule() > > if geo == 3: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > > r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) > > r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) > s.rules.append(r) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong > +datum=WGS84") > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > elif geo == 2: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > > r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) > s.rules.append(r) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong > +datum=WGS84") > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > elif geo == 1: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > blue = > mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) > blue.allow_overlap = True > s=mapnik.Style() > r=mapnik.Rule() > r.symbols.append(blue) > s.rules.append(r) > #s.rules.append(blue) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong > +datum=WGS84") > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > else: >
[Tutor] Communicating Between Programs Using Raw Inputs
Dear Python Tutors, I was wondering how to break into my one program I made using brute force methods. Here's the code: password = "Helloworld" try= raw_input("What's the password?") while try != password: try = raw_input("Incorrect, what's the password?") I know how to do it in the command line, but not through another program. Generating the random tries for the password isn't the issue, but entering the password(s) in between the two programs is an issue because I don't know how to make programs communicate through raw inputs. Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Break stament issue
Susana Iraiis Delgado Rodriguez wrote: Hello members! I'm doing a script that needs to loop to get some information, in order to do that I'm using modules from OGR and Mapnik. These to get data from shapefiles, but some of the files have 0 elements, I wrote a line to validate it, but it hasn't worked, so I added a break to keep working. When I run the scipt I got the next error: Traceback (most recent call last): File "", line 1, in import mapnik_punto_sin_duda File "C:\Python26\mapnik_punto_sin_duda.py", line 23 break ^ IndentationError: unexpected indent This error has nothing to do with break. Look at the error message, and the position of the ^ mark: the error occurs *before* the break statement, in the indentation. I can duplicate the error in Python 2.6 with this: >>> for t in (1, 2, 3): ... print t # four spaces ... break # one tab File "", line 3 break # one tab ^ IndentationError: unexpected indent Newer versions of Python give more helpful error messages: Python 3 reports "TabError: inconsistent use of tabs and spaces in indentation". You can fix this by using the tabnanny script supplied with Python. From the shell (not Python's interactive interpreter!) or the DOS prompt, run: python -m tabnanny -v replacing with the actual filename, and see what it says. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Communicating Between Programs Using Raw Inputs
Jacob Bender wrote: Dear Python Tutors, I was wondering how to break into my one program I made using brute force methods. Here's the code: password = "Helloworld" try= raw_input("What's the password?") while try != password: try = raw_input("Incorrect, what's the password?") I know how to do it in the command line, but not through another program. Generating the random tries for the password isn't the issue, but entering the password(s) in between the two programs is an issue because I don't know how to make programs communicate through raw inputs. Normally you would do this by redirecting standard input. What operating system are you using? In Linux, you would do something like: # run script foo.py taking input from the output of bar.py foo.py < bar.py at the shell. I don't know how to do it in DOS. However, I don't know if this will actually work for raw_input. It may not. Try it and see. Perhaps a better way is to have your program accept a user name and password on the command line, and only prompt for them if not given. Then you can say: foo.py --user=fred --password="y8Mr3@hzi" Hope this helps, -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Communicating Between Programs Using Raw Inputs
On 14-Jun-11 15:48, Steven D'Aprano wrote: Normally you would do this by redirecting standard input. What operating system are you using? In Linux, you would do something like: # run script foo.py taking input from the output of bar.py foo.py < bar.py Actually, no, that will send the *source code* of bar.py as the input to foo.py. I think you mean: bar.py | foo.py which also should work in DOS as well (although less efficiently). However, I don't know if this will actually work for raw_input. It may not. Try it and see. It should. Perhaps a better way is to have your program accept a user name and password on the command line, and only prompt for them if not given. Then you can say: foo.py --user=fred --password="y8Mr3@hzi" This is one way. Another would be to use the subprocess module in Python which will let one program invoke another program, and have a file-like object on which it can write data, which the child program will see as its standard input (and read in to raw_input). -- Steve Willoughby / st...@alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Communicating Between Programs Using Raw Inputs
"Jacob Bender" wrote I know how to do it in the command line, but not through another program. Generating the random tries for the password isn't the issue, but entering the password(s) in between the two programs is an issue because I don't know how to make programs communicate through raw inputs. You need to search for stdin and stdout. Try wikipedia. Then google python stdin By linking stdout of one program to stdin of another you can pass data between them. This is one of the things that makes Unix such an insanely great programmers OS, its commands are explicitly designed to do this. But you can make it work with any command that prints to stdout and reads from stdin. If you read the "Talking to the User" topic in my tutorial you will see a sidebar/box that discusses this and gives an example of reading from a file. You need to take that one step further and read from a process. In Unix the easiest way you can do that is to surround the command with backtick marks: python reader.py < `python writer.py` notice the *back* quote marks. There are other ways of doing it inside Python, seee my "Using the OS" topic for those. But backtics and stdin should do what you need. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Communicating Between Programs Using Raw Inputs
As always, Alan has given a lot of great advice and useful information. There's just one piece at the end I would question, however: On 14-Jun-11 16:36, Alan Gauld wrote: > python reader.py < `python writer.py` Almost, but not quite. The backticks mean the command is executed and the output substituted back on the command line. The < bracket means to take what follows it as a file NAME (not a data stream). So unless writer.py outputs a filename, you really want something like python writer.py | python reader.py -- Steve Willoughby / st...@alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Already Initialized Object Inheritance?
I can not get this to behave in the manor that I would like. I am trying to have an object refereed to as CursesApp.Screen become the already initialized object "stdscr". To elaborate I would like it to become that object but to also be able to define additional methods and properties, so more along the lines of inherit from "stdscr". Is this even possible? Well I can make it equal to that object I can not add additional methods and properties to it? Additionally, so that I learn; where has my thinking been too short sited? Thank you for your help. -- Jordan CODE BELOW #!/usr/bin/python3 """With thi method I can make the class "Screen" become "stdscr" but if I refernce any of the new methods or properties the applications promptly fails and notifies me that the method or property does not exist. Another downside of this method is I can not reference self.Screen.* or it crashes.""" import curses class CursesApp: def __init__(self, stdscr): self.Screen(stdscr) #This is the stdscr object. curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) #self.Screen.bkgd(' ', curses.color_pair(1)) #self.mainLoop() #def mainLoop(self): #while 1: #self.Screen.refresh() #key=self.Screen.getch() #if key==ord('q'): break class Screen: def __init__(self,stdscr): self=stdscr #self.height, self.width = self.getmaxyx() # any reference to these crashes #self.offsety, self.offsetx = -self.height/2, -self.width/2 # any reference to these crashes #self.curx, self.cury = 1, 1 # any reference to these crashes self.clear() self.border(0) while 1: self.refresh() key=self.getch() if key==ord('q'): break def main(): cursesapp = curses.wrapper(setup) def setup(stdscr): CursesApp(stdscr) if __name__ == '__main__': main() CODE BELOW #!/usr/bin/python3 """With this method I can make "Screen" become "stdscr" but if I obviously can not even define any new methods or properties. But atleast the references can be used through out the class with out crashing.""" import curses class CursesApp: def __init__(self, stdscr): self.Screen=stdscr #This is the stdscr object. curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) self.Screen.bkgd(' ', curses.color_pair(1)) self.mainLoop() def mainLoop(self): while 1: self.Screen.refresh() key=self.Screen.getch() if key==ord('q'): break def main(): cursesapp = curses.wrapper(setup) def setup(stdscr): CursesApp(stdscr) if __name__ == '__main__': main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Already Initialized Object Inheritance?
Unfortunately I am not able to inherit "stdscr" using that method. As Python returns with an error stating that "stdscr" is not defined. This error is returned at run time and by the compiler prior to actual execution. If you would like I can write a quick example that will generate the error message for that method. -- Jordan On Wed, 2011-06-15 at 02:04 -0400, Japhy Bartlett wrote: > When you're subclassing something, you use the syntax: > > class Foo(Bar): > > It seems like you're trying to do: > > class Bar: > class Foo: > > - Japhy > > On Wed, Jun 15, 2011 at 12:47 AM, WolfRage wrote: > > I can not get this to behave in the manor that I would like. I am trying > > to have an object refereed to as CursesApp.Screen become the already > > initialized object "stdscr". To elaborate I would like it to become that > > object but to also be able to define additional methods and properties, > > so more along the lines of inherit from "stdscr". Is this even possible? > > Well I can make it equal to that object I can not add additional methods > > and properties to it? Additionally, so that I learn; where has my > > thinking been too short sited? Thank you for your help. > > -- > > Jordan > > > > CODE BELOW > > > > #!/usr/bin/python3 > > """With thi method I can make the class "Screen" become "stdscr" but if > > I refernce any of the new methods or properties the applications > > promptly fails and notifies me that the method or property does not > > exist. Another downside of this method is I can not reference > > self.Screen.* or it crashes.""" > > import curses > > class CursesApp: > >def __init__(self, stdscr): > >self.Screen(stdscr) #This is the stdscr object. > >curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) > >#self.Screen.bkgd(' ', curses.color_pair(1)) > >#self.mainLoop() > > > >#def mainLoop(self): > >#while 1: > >#self.Screen.refresh() > >#key=self.Screen.getch() > >#if key==ord('q'): break > > > >class Screen: > >def __init__(self,stdscr): > >self=stdscr > >#self.height, self.width = self.getmaxyx() # any reference > > to these crashes > >#self.offsety, self.offsetx = -self.height/2, -self.width/2 > > # any reference to these crashes > >#self.curx, self.cury = 1, 1 # any reference to these > > crashes > >self.clear() > >self.border(0) > >while 1: > >self.refresh() > >key=self.getch() > >if key==ord('q'): break > > > > def main(): > >cursesapp = curses.wrapper(setup) > > > > def setup(stdscr): > >CursesApp(stdscr) > > > > if __name__ == '__main__': > >main() > > > > > > > > CODE BELOW > > > > #!/usr/bin/python3 > > """With this method I can make "Screen" become "stdscr" but if I > > obviously can not even define any new methods or properties. But atleast > > the references can be used through out the class with out crashing.""" > > import curses > > class CursesApp: > >def __init__(self, stdscr): > >self.Screen=stdscr #This is the stdscr object. > >curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) > >self.Screen.bkgd(' ', curses.color_pair(1)) > >self.mainLoop() > > > >def mainLoop(self): > >while 1: > >self.Screen.refresh() > >key=self.Screen.getch() > >if key==ord('q'): break > > > > def main(): > >cursesapp = curses.wrapper(setup) > > > > def setup(stdscr): > >CursesApp(stdscr) > > > > if __name__ == '__main__': > >main() > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor