Need help to pass self.count to other classes.

Lie Ryan lie.1296 at gmail.com
Sat Jan 9 01:14:31 EST 2010


On 1/8/2010 3:56 PM, Steven D'Aprano wrote:
> Unfortunately this won't do what you expect, because sys.ps1 and ps2
> should be either strings, or objects with a __str__ method. They aren't
> called to generate the prompt.

but their __str__ does get called to generate the prompt.

import sys

class kbInterfaceHelper(object):
      def __init__(self, str_func):
          self.str_func = str_func
      def __str__(self):
          return self.str_func()

class kbInterface(object):
     def __init__(self):
         self.count = 0
     def prompt1(self):
         self.count += 1
         return "[%d]> " % self.count
     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 = kbInterfaceHelper(kbi.prompt1)
sys.ps2 = kbInterfaceHelper(kbi.prompt2)
sys.displayhook = kbi.dhook
sys.excepthook = kbi.ehook



More information about the Python-list mailing list