Need help to pass self.count to other classes.

Francesco Bochicchio bieffe62 at gmail.com
Wed Jan 6 11:43:06 CET 2010


On 6 Gen, 11:11, Bill <bsag... at gmail.com> 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()

First of all, you shouldn't do OOP if you don't feel it. Python,
unlike Java and like C++, supports also procedural programming, so you
can write your scripts without writing classes (but still using
objects, since all in python is an object).
If you have classes with no data and a single __call_ method, then
they are no classes, they are functions (or methods) in disguise.
So, one solution could be to use plain functions and use global as you
already do. 'global' is pythonic if you are not doing OOP, although I
don't like it.

If you want to stick to OOP, then I suggest to have a make
display_hook and except_hook methods of your class SysPrompt1; This
way all your code can access to self.count without needing globals.
As for  your class SysPrompt2,  I don't understand enough your code to
know what you are trying to do. maybe make it a sunclass of
SysPrompt1 ?

HTH

Ciao
----
FB




More information about the Python-list mailing list