What is the mechanism behide?

lion dance_code at hotmail.com
Tue Sep 24 11:40:49 EDT 2002

I'm studying the singleton pattern, there are something I don't
understand in the sample code below:
class OnlyOne:
  class __OnlyOne:
    def __init__(self, arg):
      self.val = arg
    def __str__(self):
      return `self` + self.val
  instance = None
  def __init__(self, arg):
    if not OnlyOne.instance:
      OnlyOne.instance = OnlyOne.__OnlyOne(arg)
      OnlyOne.instance.val = arg
  def __getattr__(self, name):
    return getattr(self.instance, name)

print "The output:"
x = OnlyOne('sausage')
print x
y = OnlyOne('eggs')
print y
z = OnlyOne('spam')
print z
print x
print y
print `x`
print `y`
print `z`

Here are the output:
The output:
<__main__.__OnlyOne instance at 0x00C65AE0>sausage
<__main__.__OnlyOne instance at 0x00C65AE0>eggs
<__main__.__OnlyOne instance at 0x00C65AE0>spam
<__main__.__OnlyOne instance at 0x00C65AE0>spam
<__main__.__OnlyOne instance at 0x00C65AE0>spam
<__main__.OnlyOne instance at 0x00C62C58>
<__main__.OnlyOne instance at 0x00C64400>
<__main__.OnlyOne instance at 0x00C5DC20>

    I'm puzzled that what is behide the statement "print x" ? It seem
that the "print x" is implicitly turned into "print x.instance". It
was said that the redirection is steered by the function
__getattr__(self, name), but the function need two parameter, there is
only one, I mean, x. Additionally, the function __str__(self) must
also be invoked implicitly in the print-statement. Finally, the
difference  between statement "print x" and "print `x`" is also
unknown for me.
    It all like magic! Could anyone explain the mechanism for me?

Thank in advance,

More information about the Python-list mailing list