Need help to pass self.count to other classes.

Steve Holden steve at holdenweb.com
Wed Jan 6 14:56:23 CET 2010


Bill wrote:
> 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.
> 
> How can I pass in self.count without a global?
> I did RTFM, aka Google, but to no avail.
> 
> echo py.bat
> set PYTHONSTARTUP=c:\scripts\startup.py
> python
> ^Z
> 
> # startup.py
> # inspired by:
> # http://www.doughellmann.com/PyMOTW/sys/interpreter.html
> 
> import sys
> 
> class SysPrompt1(object):
>     def __init__(self):
>         self.count = 0
>     def __str__(self):
>         self.count += 1
>         global zxc
>         zxc = self.count
>         return '[%2d]> ' % self.count
> 
> class SysPrompt2(object):
>     def __str__(self):
>         global zxc
>         if zxc > 99: return '...... '
>         else: return '..... '
> 
> class DisplayHook(object):
>     def __call__(self, value):
>         if value is None: return
>         global zxc
>         if zxc > 99: print '[ out]', value, '\n'
>         else: print '[out]', value, '\n'
> 
> class ExceptHook(object):
>     def __call__(self, type, value, trace):
>         global zxc
>         if zxc > 99: print '[ err]', value, '\n'
>         else: print '[err]', value, '\n'
> 
> sys.ps1 = SysPrompt1()
> sys.ps2 = SysPrompt2()
> sys.displayhook = DisplayHook()
> sys.excepthook = ExceptHook()
> 
As Francesco points out, OO programming isn't *mandatory* in Python.

However, if you used a single class instead of multiples then you could
use an instance variable for zxc, and have each of the  functions be
bound methods (i.e. methods of the instance, not the class).

This is untested code (some days I don't seem to write any other kind
...) but it should give you the flavor:

class kbInterface(object):
    def __init__(self):
        self.zxc = 0
    def prompt1(self):
        self.count += 1
        return "[%d]> "
    def prompt2(self):
        l = len(str(self.count))+1
        return "%s " % "."*l
    def dhook(self, value):
        print "[%d out]" % self.count
    def ehook(self, type, value, trace):
        print "[%d err]\n" % value

kbi = kbInterface()
sys.ps1 = kbi.prompt1
sys.ps2 = kbi.prompt2
sys.displayhook = kbi.dhook
sys.excepthook = kbi.ehook

Do you get the idea? Now the count is shared between all the methods,
and it's available in the instance's namespace.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/




More information about the Python-list mailing list