[Tutor] detecting data member changes
Supposing I have a class like this: class wiimote(object): def __init__(self): self.leds = [0,0,0,0] def updateLEDs(self): do_stuff()#write correct output report to wiimote to toggle LEDs. So basically what I want to do is that whenever the self.leds variable is changed, the updateLEDs method is called. ( I can't call it constantly in a loop because 1) the wii remote freaks out, and 2) that seems pretty ineffiicent.) I know I could use a __setattr__ but then I'd have to access the leds using a dictionary with an 'LED' key mapped to the status array. It's not necessarily a bad thing for my own use, but it seems like it'd be off-putting to other people using my library. So is there a way to detect such changes that's Pythonic? Thanks, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] detecting data member changes
Luke Paireepinart [EMAIL PROTECTED] wrote class wiimote(object): def __init__(self): self.leds = [0,0,0,0] def updateLEDs(self): do_stuff()#write correct output report to wiimote to toggle LEDs. So basically what I want to do is that whenever the self.leds variable is changed, the updateLEDs method is called. I'm not sure what your concern is here. Since leds is an attribute of this class and therefore should only be changed by a message to this class, then it should be easy enough to ensure that each method that updates the leds calls updateLED() when it makes a change Or are you concerned about the possibility of someone directly modifying leds from outside the class (naughty!). If its the latter then you have the usual Python options: - Make it single underscored and comment the fact that mods should call update:LED() - The pythonic way of consenting adults. - Use the double underscore to make leds private - Use setattr as you describe - I'm not clear why you need dictionary access though? - Use a property to make direct access via a method - Make leds a class which uses setattr... Or am I missing something else? I know I could use a __setattr__ but then I'd have to access the leds using a dictionary with an 'LED' key mapped to the status array. It's not necessarily a bad thing for my own use, but it seems like it'd be off-putting to other people using my library. Given that users of your class shouldn't be accessing leds directly the format of the data should be of no interest to them. And a format that discourages direct access would be a good thing - provided your message interface makkes use of the class easy. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] scope/namespaces
Something in python disturbs me , when i write a for loop, i am able to access the variable declared in that loop after the loop finishes which i am not able to do in languages like c/c++ or java. Is it different in python? - Ahhh...imagining that irresistible new car smell? Check outnew cars at Yahoo! Autos.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scope/namespaces
On 4/24/07, ammar azif [EMAIL PROTECTED] wrote: i am able to access the variable declared in that loop after the loop finishes which i am not able to do in languages like c/c++ or java. Is it different in python? I'm not sure what you mean with different, but the loop-variable is not destroyed upon the exit of the for-loop: z Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'z' is not defined for z in (1,2,3): pass ... print z 3 -- - Rikard - http://bos.hack.org/cv/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter import error
On Tue, 24 Apr 2007 00:09:21 +0100 Alan Gauld [EMAIL PROTECTED] wrote: John DeStefano [EMAIL PROTECTED] wrote I've run into an error that I've seen reported in several places, but none of the fixes seem to be working for me: when I try to import Tkinter I get a configuration error: Traceback (most recent call last): File stdin, line 1, in module File /usr/local/lib/python2.5/lib-tk/Tkinter.py, line 38, in module import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter Have you specifically selected Tkinter when you compiled the code? I believe you need to set something via configure... Alternatively find an rpm with Tkinter configured already, that should be pretty easy. Usually there is no need to pass extra arguments to configure. My guess is that you missed to install Tcl / Tk and/or the Tcl/Tk development packages before compiling python. Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] detecting data member changes
Luke Paireepinart wrote: Supposing I have a class like this: class wiimote(object): def __init__(self): self.leds = [0,0,0,0] def updateLEDs(self): do_stuff()#write correct output report to wiimote to toggle LEDs. So basically what I want to do is that whenever the self.leds variable is changed, the updateLEDs method is called. ( I can't call it constantly in a loop because 1) the wii remote freaks out, and 2) that seems pretty ineffiicent.) Make leds a property: class wiimote(object): def __init__(self): self._leds = [0, 0, 0, 0] def _set_leds(self, leds): self._leds = leds self._updateLEDs() def _get_leds(self): return self._leds leds = property(_get_leds, _set_leds) def _updateLEDs(self): print self._leds w = wiimote() print w.leds w.leds = [1, 2, 3, 4] print w.leds I renamed _updateLEDs because it doesn't seem like this should be part of the public interface. If you don't like having _set_leds and _get_leds in the namespace of wiimote, use one of the recipes here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698 I know I could use a __setattr__ but then I'd have to access the leds using a dictionary with an 'LED' key mapped to the status array. It's not necessarily a bad thing for my own use, but it seems like it'd be off-putting to other people using my library. I don't understand this part. It seems to me this would work: def __setattr__(self, name, value): object.__setattr__(self, name, value) if name == 'leds': self._updateLEDs() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question on UserDict class - copy function
Hello All, I am very new to Python scripting. I have just started learning about Python. I have a question regarding UserDict class. UserDict class has a copy function which is defined as follows: def copy(self): if self.__class__ is UserDict: return UserDict(self.data) import copy return copy.copy(self) Here, as I understand, copy module is capable of making a copy of any python object. If so, why isn't this function defined as: def copy(self): import copy return copy.copy(self) In other words, what is the need to use the if statement first and then import the copy module? if self.__class__ is UserDict: return UserDict(self.data) Thanks and Regards, Ketan Joshi __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scope/namespaces
ammar azif wrote: Something in python disturbs me , when i write a for loop, i am able to access the variable declared in that loop after the loop finishes which i am not able to do in languages like c/c++ or java. Is it different in python? Yes, it is different. In Python a block is not a scope. Names bound within the block, including the loop variable, are accessible outside the block. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] + converted to 25 in http string
Hi, I am using http to automate my Access point(AP) configuration where I sent following strings to AP server through script. params = urllib.urlencode ({'WRegion':USA,'ssid':wifi,'ap':ap,'ssid_enable':ssid_enable,* 'wire_mode':b+only,* 'w_channel':6,'lan_ac':everyone,'int_ac':everyone}) Above string I captured using a tool ethereal and then implementing this in my script. But the problem is that when I run this script all configurations in AP are OK except the parameter marked as bold in above string. I used the same tool ethereal to see what string is actually passing to Access point while I run my script and I got following: params = urllib.urlencode ({'WRegion':USA,'ssid':wifi,'ap':ap,'ssid_enable':ssid_enable,* 'wire_mode':b25only,* 'w_channel':6,'lan_ac':everyone,'int_ac':everyone}) In conclusion,the character + is getting converted into25 whenever I run script.Thats why all other configuartions are OK except above mentioned case. Can anybody help to resolve this issue? Best Regards, Govind Goyal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] + converted to 25 in http string
Hi, govind goyal wrote: Hi, I am using http to automate my Access point(AP) configuration where I sent following strings to AP server through script. params = urllib.urlencode ({'WRegion':USA,'ssid':wifi,'ap':ap,'ssid_enable':ssid_enable,* 'wire_mode':b+only,* 'w_channel':6,'lan_ac':everyone,'int_ac':everyone}) You might consider having a look at the urllib quote_plus and unquote_plus methods for clarification. I suspect the value you have captured with ethereal is already quoted ('+' signs for spaces, etc) -- so you would have to unquote_plus it to find the correct value for use in your script. . urllib.unquote_plus('b+only') 'b only' And, it appears that urllib.urlencode quotes the parameters while constructing the query-string: . params = urllib.urlencode({'write_mode': 'b only'}) . params 'write_mode=b+only' HTH, Marty Above string I captured using a tool ethereal and then implementing this in my script. But the problem is that when I run this script all configurations in AP are OK except the parameter marked as bold in above string. I used the same tool ethereal to see what string is actually passing to Access point while I run my script and I got following: params = urllib.urlencode ({'WRegion':USA,'ssid':wifi,'ap':ap,'ssid_enable':ssid_enable,* 'wire_mode':b25only,* 'w_channel':6,'lan_ac':everyone,'int_ac':everyone}) In conclusion,the character + is getting converted into25 whenever I run script.Thats why all other configuartions are OK except above mentioned case. Can anybody help to resolve this issue? Best Regards, Govind Goyal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] + converted to 25 in http string
govind goyal wrote: Hi, I am using http to automate my Access point(AP) configuration where I sent following strings to AP server through script. params = urllib.urlencode({'WRegion':USA,'ssid':wifi,'ap':ap,'ssid_enable':ssid_enable,*'wire_mode':b+only,* 'w_channel':6,'lan_ac':everyone,'int_ac':everyone}) Above string I captured using a tool ethereal and then implementing this in my script. But the problem is that when I run this script all configurations in AP are OK except the parameter marked as bold in above string. '+' is not a valid character in parameters so it is escaped to %2B by urlencode: In [10]: import urllib In [11]: params = urllib.urlencode({'WRegion':USA,'ssid':wifi,'ap':ap,'ssid_enable':ssid_enable,'wire_mode':b+only, 'w_channel':6,'lan_ac':everyone,'int_ac':everyone}) In [12]: params Out[12]: 'ssid=wifissid_enable=ssid_enableap=apint_ac=everyoneWRegion=USAw_channel=6lan_ac=everyonewire_mode=b%2Bonly' I used the same tool ethereal to see what string is actually passing to Access point while I run my script and I got following: params = urllib.urlencode({'WRegion':USA,'ssid':wifi,'ap':ap,'ssid_enable':ssid_enable,*'wire_mode':b25only, *'w_channel':6,'lan_ac':everyone,'int_ac':everyone}) Where did this come from? This is not the output of ethereal... In conclusion,the character + is getting converted into25 whenever I run script.Thats why all other configuartions are OK except above mentioned case. Interestingly, %25 is the escaped representation of '%'. So I wonder if your parameters are being url-encoded twice? Can you show a little more of your code, and the actual string captured from ethereal? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scope/namespaces
Sorry about that kent. I just realized I emailed you directly. Ezra On 4/24/07, Kent Johnson [EMAIL PROTECTED] wrote: ammar azif wrote: Something in python disturbs me , when i write a for loop, i am able to access the variable declared in that loop after the loop finishes which i am not able to do in languages like c/c++ or java. Is it different in python? Yes, it is different. In Python a block is not a scope. Names bound within the block, including the loop variable, are accessible outside the block. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Ezra Taylor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scope/namespaces
Ezra Taylor wrote: Hello Kent: How can we limit this functionality so that python behaves similar to other know languages. Maybe I should be asking what are the benifits of allow variables not being bound to a block of code. Why is this a problem? Don't try to turn Python into Java, you might as well stay with Java. One advantage is, you can define a variable in a conditional block or a try block without having to declare it first. For example: if something: x = 3 else: x = 5 or try: x = foo() finally: cleanup() # do something with x It has long annoyed my that in Java these snippets would have to be prefixed with int x; Kent Ezra On 4/24/07, *Kent Johnson* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: ammar azif wrote: Something in python disturbs me , when i write a for loop, i am able to access the variable declared in that loop after the loop finishes which i am not able to do in languages like c/c++ or java. Is it different in python? Yes, it is different. In Python a block is not a scope. Names bound within the block, including the loop variable, are accessible outside the block. Kent ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Ezra Taylor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter import error
Michael Lange [EMAIL PROTECTED] wrote: Usually there is no need to pass extra arguments to configure. My guess is that you missed to install Tcl / Tk and/or the Tcl/Tk development packages before compiling python. That was it: I had both Tcl and Tk installed, but not the development packages for either one. I installed those, recompiled, and all is well. Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] detecting data member changes
Make leds a property: class wiimote(object): def __init__(self): self._leds = [0, 0, 0, 0] def _set_leds(self, leds): self._leds = leds self._updateLEDs() def _get_leds(self): return self._leds leds = property(_get_leds, _set_leds) def _updateLEDs(self): print self._leds w = wiimote() print w.leds w.leds = [1, 2, 3, 4] print w.leds Wow, that's cool. I need to read more about properties. I renamed _updateLEDs because it doesn't seem like this should be part of the public interface. Yeah, it was prepended with an underscore in my code, I forgot to put it when I simplified the code here. *embarrassed* If you don't like having _set_leds and _get_leds in the namespace of wiimote, use one of the recipes here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698 I know I could use a __setattr__ but then I'd have to access the leds using a dictionary with an 'LED' key mapped to the status array. It's not necessarily a bad thing for my own use, but it seems like it'd be off-putting to other people using my library. I don't understand this part. It seems to me this would work: def __setattr__(self, name, value): object.__setattr__(self, name, value) if name == 'leds': self._updateLEDs() What I meant was that it'd require people to access the variable via classinstance['leds'] instead of classinstance.leds which is what I was aiming for. I apologize, I should've waited till the morning to e-mail so I could be more coherent. Is this properties method acceptable Python form or is it more proper to have modifying member functions like Alan said? Or is it really up to me on how I want to implement it? Thanks, -Luke Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on UserDict class - copy function
On 4/24/07, Ketan Joshi [EMAIL PROTECTED] wrote: If so, why isn't this function defined as: def copy(self): import copy return copy.copy(self) The if-case in your code makes sure that the property __class__ is of UserDict-inheritance. I believe it's there in case of multiple classes. class Gas: def __init__(self): pass class Oil: def __init__(self): self.foo = Gas() self.dict = UserDict() b = Oil() b.__class__ will be __main__.Oil, and if you pass the entire class around and want a copy of the dict-property, the copy()-method in UserDict will first it is a UserDict-instance before copying it. If it isn't, it creates one out of the existing data. -- - Rikard - http://bos.hack.org/cv/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] detecting data member changes
Luke Paireepinart wrote: I know I could use a __setattr__ but then I'd have to access the leds using a dictionary with an 'LED' key mapped to the status array. It's not necessarily a bad thing for my own use, but it seems like it'd be off-putting to other people using my library. I don't understand this part. It seems to me this would work: def __setattr__(self, name, value): object.__setattr__(self, name, value) if name == 'leds': self._updateLEDs() What I meant was that it'd require people to access the variable via classinstance['leds'] instead of classinstance.leds which is what I was aiming for. I apologize, I should've waited till the morning to e-mail so I could be more coherent. No, the above code should work with classinstance.leds. Maybe you are confusing __setattr__ - which affects attributes like .leds - with __setitem__ which is used for classinstance['leds'] Is this properties method acceptable Python form or is it more proper to have modifying member functions like Alan said? Alan and I don't always agree on questions like this. I don't take such a hard position about direct attribute access. IMO using a property is more Pythonic than making an explicit method. But I think one of the nice things about Python is you don't have to write explicit getters and setters; you can use plain attribute access to get at plain data, then if you need to add some behaviour just change the attribute to a property. Or is it really up to me on how I want to implement it? Of course, it's your code, right? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to stop a function
hello all, i have a gui app that uses functions to respond to gui events. like def on_start_button_clicked(self, stuff): do this or that. now there is one function that i have a kinda nested if else conditions that i need to stop if necessary if value == 1: if next_val == 4: do this or that else: here i need the function to just die do somthing here is there something i can do to make this happen? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: how to stop a function
-- Forwarded message -- From: Andre Engels [EMAIL PROTECTED] Date: 24 apr. 2007 17:18 Subject: Re: [Tutor] how to stop a function To: shawn bright [EMAIL PROTECTED] 2007/4/24, shawn bright [EMAIL PROTECTED]: hello all, i have a gui app that uses functions to respond to gui events. like def on_start_button_clicked(self, stuff): do this or that. now there is one function that i have a kinda nested if else conditions that i need to stop if necessary if value == 1: if next_val == 4: do this or that else: here i need the function to just die else: return -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to stop a function
shawn bright wrote: now there is one function that i have a kinda nested if else conditions that i need to stop if necessary if value == 1: if next_val == 4: do this or that else: here i need the function to just die do somthing here is there something i can do to make this happen? return Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to stop a function
jeeze, thanks, sorry, stupid question. On 4/24/07, Kent Johnson [EMAIL PROTECTED] wrote: shawn bright wrote: now there is one function that i have a kinda nested if else conditions that i need to stop if necessary if value == 1: if next_val == 4: do this or that else: here i need the function to just die do somthing here is there something i can do to make this happen? return Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] detecting data member changes
No, the above code should work with classinstance.leds. Maybe you are confusing __setattr__ - which affects attributes like .leds - with __setitem__ which is used for classinstance['leds'] Ah, yes. You hit the hail on the nead there, Kent. Thanks for clarifying that for me. Is this properties method acceptable Python form or is it more proper to have modifying member functions like Alan said? Alan and I don't always agree on questions like this. I don't take such a hard position about direct attribute access. IMO using a property is more Pythonic than making an explicit method. But I think one of the nice things about Python is you don't have to write explicit getters and setters; you can use plain attribute access to get at plain data, then if you need to add some behaviour just change the attribute to a property. I can see how some people might be surprised to know that changing classinstance.leds automagically sends a communication packet to the wii remote without their knowledge, but if they're aware of the side-effect, it seems to be a more elegant way of doing things to me (with properties vs. an explicit method), at least in this case. Or is it really up to me on how I want to implement it? Of course, it's your code, right? Yes, but it's code I plan on open-sourcing, so I'm trying to make it clear what's happening in case I get other developers to help in the future. -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exceptions while dealing with MySQL
Thanks to everybody for the replies. I got some nice pointers. I know my design is nasty, but that is because I am learning...Putting object orientation in the mix, I have this question: I have an object, person, which is assosiated with some statistical data. Say for each person object, I need an object variable called hairColor. This haircolor variable has to be filled through an SQL query, so the object must have some way to access a database cursor. The cool thing would be that all person objects use the same connection/cursor to get their haircolors filled in, so there would be only one connection to the SQL server. Could this done with a class variable? From what I understand, it fits nice because its available to all objects of the class, and it is unique. So would this be a nice way to have objects of the same class share a pipe to the sql database? On 4/23/07, Alan Gauld [EMAIL PROTECTED] wrote: Kent Johnson [EMAIL PROTECTED] wrote I like Martin Fowler's Patterns of Enterprise Application Architecture. I agree, except the title can be slightly misleading. Just to make it clear, the book is about application architecture for larger scale applications (not really enterprise scale just larger scale than the usual book examples) and has virtually nothing to say about enterprise architecture in the sense of say Zachman etc. But as a book about application architectures its a very good guide. I rate it along with Booch's classic OOAD book which deals with similar issues in a different context. Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] detecting data member changes
Luke Paireepinart wrote: I can see how some people might be surprised to know that changing classinstance.leds automagically sends a communication packet to the wii remote without their knowledge, but if they're aware of the side-effect, it seems to be a more elegant way of doing things to me (with properties vs. an explicit method), at least in this case. I think so. Or is it really up to me on how I want to implement it? Of course, it's your code, right? Yes, but it's code I plan on open-sourcing, so I'm trying to make it clear what's happening in case I get other developers to help in the future. Using properties in this way is accepted practice. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to stop a function
On 4/24/07, shawn bright [EMAIL PROTECTED] wrote: is there something i can do to make this happen? Use the keyword return. -- - Rikard - http://bos.hack.org/cv/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] detecting data member changes
Luke Paireepinart [EMAIL PROTECTED] wrote Is this properties method acceptable Python form or is it more proper to have modifying member functions like Alan said? Properties is fine and was one of the options that I suggested. However I didn't mean you should have modifying member functions in the sense of set/get merthods - I actually hate those generally! What I meant is that, whatever a wiimote is, it should be offering up a behaviour oriented inteface that, as a side-effect, changes the internal leds attribute. OOP is all about abstracting some higher level object into a set of behaviours. The attributes of an object should only really be there to support those higher behaviours. So what is it that a wiimote does? And how does that behaviour affect the leds? That is the set of methods to build. (Since I've never heard of a wiimote I have no idea what the abstract behaviour might be!) For example, if I build a lamp object I might have an _isLit boolean attribute internally. Now I could write a method to set the _isLit attribute to True or False lamp = Lamp() lamp.setIsLit(True) lamp.setIsLit(False) And superficioally it looks like OK code that does the job. But that's not how people intuitively think of lamps. They light them or turn them off. So the code is better if the Lamp class provides on/off methods that control the _isLit attribute: lamp = Lamp() lamp.on() lamp.off() And its easier to use so there no temptaiuon to mess with the attribute directly and I can change the _isLit type from Boolean to a number or a string or whatever I want and the client code is unaffected. Thats what I mean about providing a message interface that negates the need for users of the class to know or care about the leds attribute. If you make it intuitive and easy to use the class via messages then there is no incentive to go messing with the internals. However if you do need direct access to a data attribute then direct access is usually OK. If the class is primarily there to store some bit oif data (but that should be the exception in OOP) then you might as well offer direct access as write get/set methods But if you want to ensure some kind of behaviour is associated with the attribute then use a property or setattr(). Or is it really up to me on how I want to implement it? Ultimately, it's always up to the programmer how you implement it! :-) But some techniques make your life a bit easier is all. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] No return statement
My apologies for asking a trivial question about programming practice. As mentioned in the online tutorial (http://docs.python.org/tut/node6.html#SECTION00670), functions which lack a return statement ('procedures') actually return None. For such functions, I assume it's preferred to not catch None in a variable. Example: def printme(x): print x Preferred function call: printme(10) 10 Alternative (where None is caught into z): z = printme(10) 10 (And then one could print None) print z None ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scope/namespaces
ammar azif [EMAIL PROTECTED] wrote Something in python disturbs me , when i write a for loop, i am able to access the variable declared in that loop after the loop finishes which i am not able to do in languages like c/c++ or java. That's a very recent change to C/C++ (1999 apparently), you used to be able to do that. In fact I hadn't realised that you couldn't any more! It was only when I wrote a test program I discovered you were right... Is it different in python? Yes. Once you create a name within a scope it stays there and loops or code blocks are not a separate scope in Python -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scope/namespaces
Ezra Taylor wrote: How can we limit this functionality so that python behaves similar to other know languages. There are many other languages that work like Python. Including the original versions of C and C++... And other languages that don't have explicit loop constructs at all! Others only have while loops... Maybe I should be asking what are the benifits of allow variables not being bound to a block of code. For one thing you can find out how far a loop got to if it was exited via a break. for n in range(25): if doit(item[n]) == False: break print 'The loop stopped at item', n There are lots of things that languages do differently, otherwise there would be no point in having different languages! Embrace the differences as an opportunity to see things differently. ;-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Clarification on Debugging under IDLE
On the debug control, what is the difference between go, over, and out? Thank you, J.T. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exceptions while dealing with MySQL
Thanos Panousis [EMAIL PROTECTED] wrote data. Say for each person object, I need an object variable called hairColor. This haircolor variable has to be filled through an SQL query, so the object must have some way to access a database cursor. The cool thing would be that all person objects use the same connection/cursor to get their haircolors filled in, so there would be only one connection to the SQL server. Could this done with a class variable? From what I understand, it fits nice because its available to all objects of the class, Absolutely and that would be a good choice provided you don't need connections/cursors from each class to the same database. If that's the case you may prefer to create the connection globally and pass a reference into your classes via init. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] No return statement
My opinion is that one should not create or set a variable if its value is not used. In the case mentioned, you know what the return value will be, so there seems to be no reason to keep it. 2007/4/24, Cecilia Alm [EMAIL PROTECTED]: My apologies for asking a trivial question about programming practice. As mentioned in the online tutorial (http://docs.python.org/tut/node6.html#SECTION00670), functions which lack a return statement ('procedures') actually return None. For such functions, I assume it's preferred to not catch None in a variable. Example: def printme(x): print x Preferred function call: printme(10) 10 Alternative (where None is caught into z): z = printme(10) 10 (And then one could print None) print z None ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exceptions while dealing with MySQL
Thanos Panousis wrote: I have an object, person, which is assosiated with some statistical data. Say for each person object, I need an object variable called hairColor. This haircolor variable has to be filled through an SQL query, so the object must have some way to access a database cursor. The cool thing would be that all person objects use the same connection/cursor to get their haircolors filled in, so there would be only one connection to the SQL server. Could this done with a class variable? From what I understand, it fits nice because its available to all objects of the class, and it is unique. So would this be a nice way to have objects of the same class share a pipe to the sql database? Perhaps you should look into object-relational mappers such as SQLObject or SQLAlchemy. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] No return statement
OK, that's my opinion too. Thanks! 2007/4/24, Andre Engels [EMAIL PROTECTED]: My opinion is that one should not create or set a variable if its value is not used. In the case mentioned, you know what the return value will be, so there seems to be no reason to keep it. 2007/4/24, Cecilia Alm [EMAIL PROTECTED]: My apologies for asking a trivial question about programming practice. As mentioned in the online tutorial (http://docs.python.org/tut/node6.html#SECTION00670), functions which lack a return statement ('procedures') actually return None. For such functions, I assume it's preferred to not catch None in a variable. Example: def printme(x): print x Preferred function call: printme(10) 10 Alternative (where None is caught into z): z = printme(10) 10 (And then one could print None) print z None ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels -- E. Cecilia Alm Graduate student, Dept. of Linguistics, UIUC Office: 2013 Beckman Institute ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clarification on Debugging under IDLE
J.T. Hurley wrote: On the debug control, what is the difference between go, over, and out? What debug control are you using? Debuggers usually have three kinds of stepping. The names vary but the concepts are the same: step in - execute the next line of code; if it is a subroutine call, stop at the first line of code in the subroutine step over - execute the next line of code; if it is a subroutine call, execute the entire subroutine and stop at the line of code after the call step out - execute the current subroutine until reaching a return statement Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] No return statement
Cecilia Alm [EMAIL PROTECTED] wrote functions which lack a return statement ('procedures') actually return None. For such functions, I assume it's preferred to not catch None in a variable. You can catch it if you like, but since functions with no return *always* return None there is little point. You know what the value will be before you even call the function. Where catching the value is more important is where the function only has some return statements: def f(x): if x: return 42 Now f() returns None if x is not True so it makers sense to catch the reurn value and test for None. But such a function style is very bad practice IMHO! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clarification on Debugging under IDLE
J.T. Hurley [EMAIL PROTECTED] wrote On the debug control, what is the difference between go, over, and out? Cabeat, I haven't checked, but from memory: go = Run the program from the current point onwards until you hit the next break point or until it ends. over = step over the function on the current line (ie don't step into it) out = run the rest of the function and stop when you exit it back to the level above. Often used to fix an accidental step-into Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scope/namespaces
Am I wrong in my memory? When I was a wee lad prior to 99 for sure), I thought I would initialize my loops with: for (int x=0; x 10; x++) { } I am rapidly veering off topic. On 4/24/07, Alan Gauld [EMAIL PROTECTED] wrote: Correcting my own post! Alan Gauld [EMAIL PROTECTED] wrote That's a very recent change to C/C++ (1999 apparently), Actually only a recent change in C. Its always been true of C++. But in C up until recently(*) you couldn't define a loop variable in the loop it had to be outside: int x; for (x=0;) (*)I'm not sure whether the C++ style loop definition was introduced in the original ANSI standard or the later revision (none of my books malke it clear), but I think it was the revision. But C++ always had loop variables as part of block scope. Sory for any confusion, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exceptions while dealing with MySQL
I checked the SQLAlchemy and SQLObject projects, but they are not really relevant to what I am doing(moreover they are more than I can chew just yet:). I managed to get a class variable to hold a cursor via something like class person: cursor = MySQLdb.connect(stuff).cursor() BUT when I make a function inside my class called myConnect, where I do error checking and so on, I can't make it work: class person: cursor = myConnect() __init(self)___: more things here myConnect(self): try: return MySQLdb.connect(stuff).cursor() catch: print Error! When trying to run this I get NameError: name 'myConnect' is not defined. Any pointers for my OO-blindness? Thanks a lot... On 4/24/07, Kent Johnson [EMAIL PROTECTED] wrote: Thanos Panousis wrote: I have an object, person, which is assosiated with some statistical data. Say for each person object, I need an object variable called hairColor. This haircolor variable has to be filled through an SQL query, so the object must have some way to access a database cursor. The cool thing would be that all person objects use the same connection/cursor to get their haircolors filled in, so there would be only one connection to the SQL server. Could this done with a class variable? From what I understand, it fits nice because its available to all objects of the class, and it is unique. So would this be a nice way to have objects of the same class share a pipe to the sql database? Perhaps you should look into object-relational mappers such as SQLObject or SQLAlchemy. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clarification on Debugging under IDLE
Kent: I'm using IDLE's built-in debugger. Alan: I just tried it out, and you were spot-on. Thank you both for your assistance. I think I've got the hang of it now. It'll certainly speed me up now that I don't have to step through each function. Thanks again, J.T. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exceptions while dealing with MySQL
Thanos Panousis [EMAIL PROTECTED] wrote in I managed to get a class variable to hold a cursor via something like class person: cursor = MySQLdb.connect(stuff).cursor() BUT when I make a function inside my class called myConnect, where I do error checking and so on, I can't make it work: Your Python OOP is a bit mixed up here. class person: cursor = myConnect() __init(self)___: more things here You need to add def statements and the underscores come before the parens def __init__(self) myConnect(self): Similarly here. BUT this is an instance method (via the self parameter), it will not work at the class level. try: return MySQLdb.connect(stuff).cursor() catch: And this should be except not catch... print Error! When trying to run this I get NameError: name 'myConnect' is not defined. Any pointers for my OO-blindness? You can just make the connect call directly at the class level. class Person: cursor = MySQLdb.connect(...).cursor() You can then access it in your objects methods using either self.cursor or Person.cursor Personally I prefer the second since it makes it clear its a class variable... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scope/namespaces
Ben Sherman schreef: Am I wrong in my memory? When I was a wee lad prior to 99 for sure), I thought I would initialize my loops with: for (int x=0; x 10; x++) { } If that was in C, it must have been a special feature of your compiler. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scope/namespaces
Ben Sherman [EMAIL PROTECTED] wrote Am I wrong in my memory? When I was a wee lad prior to 99 for sure), I thought I would initialize my loops with: for (int x=0; x 10; x++) { You certainly could in C++ but I'm less sure about C. You certainly couldn't do that in C prior to ANSI C (in 1991/2?). However I don't think the C++ bits got incorporated into C until the C update in '99. However that didn't stop some compilers supporting them. For example the C++ // comment style was supported by most ANSI compilers even though it wasn't in the original ANSI standard. I am rapidly veering off topic. Me too :-) Alan G. Who hasn't used vanilla C in anger for at least 10 years! (And C++ for 4 or 5...) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clarification on Debugging under IDLE
Kent Johnson wrote: J.T. Hurley wrote: On the debug control, what is the difference between go, over, and out? What debug control are you using? Debuggers usually have three kinds of stepping. The names vary but the concepts are the same: step in - execute the next line of code; if it is a subroutine call, stop at the first line of code in the subroutine step over - execute the next line of code; if it is a subroutine call, execute the entire subroutine and stop at the line of code after the call step out - execute the current subroutine until reaching a return statement I should add go/continue/run - run until a breakpoint is hit, or the program ends run to cursor - set a temp breakpoint at the line containing the cursor, then go ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor