Re: [Tutor] calling setters of superclasses
Gregory, Matthew wrote: > Hi all, > > Consider the following classes where PositiveX should constrain the > attribute _x to be positive and SmallX should further constrain the > attribute _x to be less than 10. > > class PositiveX(object): > def __init__(self): > self._x = 1 > @property > def x(self): > return self._x > @x.setter > def x(self, val): > if val < 0: > raise ValueError('Negatives not allowed') > self._x = val > > class SmallX(PositiveX): > @property > def x(self): > return self._x > @x.setter > def x(self, val): > # How do I call the superclass' @x.setter > super(SmallX, self).__setattr__('x', val) > if val > 10: > raise ValueError('Big values not allowed') > self._x = val > > I thought I could call the superclass setter first to ensure the value was > positive, but I'm getting an infinite recursion. I also tried: > > super(SmallX, self).x = val > > but I get this: > > AttributeError: 'super' object has no attribute 'x' > > I'm fully confused and, therefore, likely doing something stupid. I don't think /how/ you are trying it is stupid though I'm not so sure about /what/ . I didn't get it to work with super() either, so here's Plan B till someone is going to enlighten both of us: class SmallX(PositiveX): @property def x(self): return self._x @x.setter def x(self, val): if val > 10: raise ValueError('Big values not allowed') PositiveX.x.__set__(self, val) Personally, I would more or less follow Alan's advice and do something like class PositiveX(object): def __init__(self): self._x = 1 def check_x(self, val): if val < 0: raise ValueError('Negatives not allowed') @property def x(self): return self._x @x.setter def x(self, val): self.check_x(val) self._x = val class SmallX(PositiveX): def check_x(self, val): super(SmallX, self).check_x(val) if val > 10: raise ValueError('Big values not allowed') Peter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] why "ifconfig" is alway running?
my script is #!/usr/bin/env python import datetime import subprocess import sys import os import signal from time import sleep def runForAWhile(cmd, secs=10): print("running %s" % cmd) timeout = datetime.timedelta(seconds=secs) print timeout proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) status = proc.poll() start = datetime.datetime.now() while (status is None and (datetime.datetime.now() - start) < timeout): #not timed out #print proc.stdout.readline() #TODO timestamp? print status #print datetime.datetime.now() - start if 0 == status: print("'%s' is program exited" %cmd) else: try: os.kill(proc.pid, signal.SIGINT) print "Process timeout: '%s'" % cmd except OSError: pass cmd="ifconfig" runForAWhile(cmd,10) why it print many "None" in 10 second. which means "ifconfig" is running in 10sec, why, what's wrong withi my script, I just want to let my programe running, if it's timeout(10sec), kill it Lei ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] calling setters of superclasses
On Sat, Dec 18, 2010 at 11:06 AM, Peter Otten <__pete...@web.de> wrote: > > I don't think /how/ you are trying it is stupid though I'm not so sure about > /what/ . > > I didn't get it to work with super() either, so here's Plan B till someone > is going to enlighten both of us: > By no means a solution, but I've spent some time with this in the python debugger and have some ideas. The problem is not super, as it does its job at calling __setattr__ of the base object class. __setattr__, however, resolves to the x object that is bound to self, which is SmallX.x, and not PositiveX.x, and this is what causes the recursion. So what you actually need is something like super(SmallX, self).x.__set__, but that unfortunately doesn't work either since super will use __getattr__ to resolve x, which will just result in the property getter being called. So in general, properties don't jive well with inheritance of their containing objects. I'm not sure if this behavior can be considered a bug. My idea would be to create separate descriptor classes and contain the constraints within them. The functionality has nothing to do with the containing class anyway, so it might actually simplify the design. Here's the basic idea: class UnsignedProp(object): def __init__(self, val): self.x = val def __get__(self, instance, owner): return self.x def __set__(self, instance, val): if val < 0: raise ValueError("Negatives not allowed") self.x = val class SmallProp(UnsignedProp): def __set__(self, instance, val): if val > 10: raise ValueError("value too large") super(SmallProp, self).__set__(instance, val) class X(object): x = SmallProp(1) y = UnsignedProp(1) a = X() a.x = 5 a.x = 25 # will raise ValueError ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why "ifconfig" is alway running?
"lei yang" wrote def runForAWhile(cmd, secs=10): proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) status = proc.poll() start = datetime.datetime.now() while (status is None and (datetime.datetime.now() - start) < timeout): #not timed out print status if 0 == status: print("'%s' is program exited" %cmd) else: try: os.kill(proc.pid, signal.SIGINT) why it print many "None" in 10 second. which means "ifconfig" is running in 10sec, why, what's wrong withi my script, You only check the status once *before* entering the while loop. You need another status check inside the loop. I just want to let my programe running, if it's timeout(10sec), kill it Its not clear from your mail if you have checked whether the process really is running - using the OS commands 'top' or 'ps' for example or whjether its just the None result you are concerned about. But try updating status first... 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
[Tutor] looking for python or django SQL data editor
phpmyadmin and other such mysql db design/maintain tools do too much, too complicated. I'm looking for a python or django web app that allows non-tech users to add/delete/search records. thanks Len ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] looking for python or django SQL data editor
On Sat, Dec 18, 2010 at 7:45 PM, Len Conrad wrote: > phpmyadmin and other such mysql db design/maintain tools do too much, too > complicated. > > I'm looking for a python or django web app that allows non-tech users to > add/delete/search records. You'll probably find the same here. A bunch of functions and utilities that are useless to the project at hand within frameworks. Although I'm sure it would be more helpful if you start rolling your own and asking from there. -- All comments shoukd be taken with a grain of salt, and thorough review of aforementioned material should be reviewed by the student...understood...self learner? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Template Pattern
Karim wrote: class InputStrategy( object ): """This InputStrategy class is an abstract interface to various read strategy objects. """ def read(self, filePath): """Abstract method to load into database memory an input file. @arg: filePath - string - The input file path. @return: The created database object. """ raise NotImplementedError By the way, I use NotImplementedError in my abstract method of the abstract class. You are using TypeError exception. Is there a general rule for that? NotImplementedError is ok? For abstract methods that should be overridden by a subclass, I would use NotImplementedError, as you do. That is a clear convention for saying "this method must be overridden". But __init__ is a special case. The __init__ method isn't merely not implemented. It *is* implemented, and it does two jobs: it performs any common initialization for the class and all subclasses, and it also prevents the AbstractCLass from being instantiated. class AbstractClass: def __init__(self, *args): if type(self) is AbstractClass: raise TypeError # do common initialization here Trying to instantiate an AbstractClass is always an error: instance = AbstractClass(args) and the error is a *type* error -- you are trying to instantiate a type that can't be. Python already does that, with the singletons None, NotImplemented (different from NotImplementedError!), and Ellipsis: >>> type(None)() Traceback (most recent call last): File "", line 1, in TypeError: cannot create 'NoneType' instances TypeError means you have an error in your code. NotImplementedError means the code is incomplete. I knew from Java experience that template method pattern is only a kind of particular case of Stategy where you delegate parts of algorithm by abstract methods overriding. Indeed the base class implements some common features and let derived classes implement particular parts by polymorphism. Now with your example, I don't understand why he had problems to implement from C++ ? Or perhaps is he mixing it with C++ feature template ?! You'd have to ask him. Maybe he's just not a very good programmer, or was having a bad day. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python using version 3.1
Hello I am working through a purchased text book Python programming for beginners. Chapter two shows how to create a basic program using triple-quoted strings. I am having problems working out what I have done incorrectly. The game over block writing should stay on the same line but the bottom half of the word over comes up next to the top half of the word over. Hope that makes sense. My code is as follows: # Game Over - Version 2 # Demonstrates the use of quotes in strings print("Program 'Game Over' 2.0") print("Same", "message", "as before") print("Just", "a bit", "bigger") print("Here", end=" ") print("it is...") print( """ _ __ ___ / | /| / |/ | | ___| | |/ / | |/ /| / | | |__ | | _/ | / / |__/| | | __| | |_| | / / | | / / | | | |___ \_/ /_/|_| /_/ |_| |_| _ _ _ _ / __ \ | | / / | ___| | _ \ || || | | / / | |__ | |_| | || || | | / / | __| | _ / ||__|| | |/ /| |___ | | \ \ \/ |___/ |_| |_| \_\ """ ) input("\n\nPress the enter key to exit.") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python using version 3.1
On Sun, Dec 19, 2010 at 4:42 AM, Lea Parker wrote: > Hello > > I am working through a purchased text book Python programming for beginners. > Chapter two shows how to create a basic program using triple-quoted strings. > > I am having problems working out what I have done incorrectly. The game over > block writing should stay on the same line but the bottom half of the word > over comes up next to the top half of the word over. Hope that makes sense. > It's the backslashes. A backslash at the end of a line means to disregard the newline. You need to "escape" the backslash with another backslash. See here: >>> print """this string \ ... won't have a newline, or a slash in it""" this string won't have a newline, or a slash in it >>> print """this string \\ ... will""" this string \ will The R ends in backslashes, so you need to double those up. Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why "ifconfig" is alway running?
#!/usr/bin/env python import datetime import subprocess import sys import os import signal from time import sleep def runForAWhile(cmd, secs=10): print("running %s" % cmd) timeout = datetime.timedelta(seconds=secs) print timeout proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) status = proc.poll() start = datetime.datetime.now() while (status is None and (datetime.datetime.now() - start) < timeout): #not timed out print proc.stdout.readline() #TODO timestamp? #print status #print datetime.datetime.now() - start if 0 == status: print("'%s' is program exited" %cmd) else: try: os.kill(proc.pid, signal.SIGINT) print "Process timeout: '%s'" % cmd except OSError: pass cmd="ping 128.224.165.20 -c 4" runForAWhile(cmd,30) I see that "status" always "!=0“ why program is NOT exited Lei On Sun, Dec 19, 2010 at 1:15 AM, Alan Gauld wrote: > > "lei yang" wrote > >> def runForAWhile(cmd, secs=10): >> proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, >> >> stderr=subprocess.STDOUT, shell=True) >> status = proc.poll() >> start = datetime.datetime.now() >> while (status is None and > > (datetime.datetime.now() - start) < timeout): #not timed out >> >> print status >> if 0 == status: >> print("'%s' is program exited" %cmd) >> else: >> try: >> os.kill(proc.pid, signal.SIGINT) > >> why it print many "None" in 10 second. which means "ifconfig" is >> running in 10sec, why, what's wrong withi my script, > > You only check the status once *before* entering the while loop. > You need another status check inside the loop. > >> I just want to let my programe running, if it's timeout(10sec), kill it > > Its not clear from your mail if you have checked whether the > process really is running - using the OS commands 'top' or 'ps' > for example or whjether its just the None result you are concerned > about. But try updating status first... > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ___ > Tutor maillist - tu...@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
Re: [Tutor] Python using version 3.1
On Sat, Dec 18, 2010 at 8:13 PM, Hugo Arts wrote: > On Sun, Dec 19, 2010 at 4:42 AM, Lea Parker wrote: >> I am having problems working out what I have done incorrectly. The game over >> block writing should stay on the same line but the bottom half of the word >> over comes up next to the top half of the word over. Hope that makes sense. > > It's the backslashes. > > A backslash at the end of a line means to disregard the newline. You > need to "escape" the backslash with another backslash. See here: > print """this string \ > ... won't have a newline, or a slash in it""" > this string won't have a newline, or a slash in it print """this string \\ > ... will""" > this string \ > will > > The R ends in backslashes, so you need to double those up. correct me if i'm wrong, but speaking of R, i think putting an 'r' or 'R' in front of the opening triple quotes to turn it into a raw string will make it so that you *wouldn't* have to double everything up. by the way... welcome to Python!! :-) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor