Bill a écrit :
After a year with Python 2.5 on my Windows box, I still have trouble
understanding classes.
Below, see the batch file and the configuration script for
my Python interactive prompt.
The widths of the secondary prompts increase when the self.count of
SysPrompt1 exceeds 99.
I am using a global variable "zxc" to share self.count, which is not
Pythonic.
It's not "unpythonic" - but it's not good OO style neither !-)
How can I pass in self.count without a global?
(snip)
sys.ps1 = SysPrompt1()
sys.ps2 = SysPrompt2()
sys.displayhook = DisplayHook()
sys.excepthook = ExceptHook()
hint #1: a bound method is also a callable.
hint #2: an object can be an attribute of another object.
Possible OO solution:
class Counter(object):
def __init__(self):
self._count = 0
def inc(self):
self._count += 1
value = property(fget=lambda s: s._count)
class Prompt1(object):
def __init__(self, counter):
self._counter = counter
def _str_(self):
self._counter.inc()
return '[%2d]> ' % self._counter.value
class Prompt2(object):
def __init__(self, counter):
self._counter = counter
def _str_(self):
if self._counter.value > 99: # XXX magic number
return '...... '
else:
return '..... '
class MySysHookHandler(object):
def __init__(self):
self._counter = Counter()
self.ps1 = Prompt1(self._counter)
self.ps2 = Prompt2(self._counter)
def displayhook(self, value):
if value is None:
return
if self._counter.value > 99: # XXX magic number
print '[ out]', value, '\n'
else:
print '[out]', value, '\n'
def excepthook(self, type, value, trace):
if self._counter.value > 99: # XXX magic number
print '[ err]', value, '\n'
else:
print '[err]', value, '\n'
handler = MySysHook()
sys.ps1 = handler.ps1
sys.ps2 = handler.ps2
sys.displayhook = handler.displayhook
sys.excepthook = handler.excepthook
HTH
--
http://mail.python.org/mailman/listinfo/python-list