[help] Is it true to call obj.__str__() while executing "print obj"?

Tommy Zong tzong at sigma-rt.com
Thu Nov 30 02:03:18 CET 2006


Hi,

 

I am learning metaclass by reading "Metaclass programming in Python, Part
2". I have a question as following and had tried to search from internet and
also have read the article "Unifying types and classes in Python 2.2" but
failed to get satisfied answer. Could you please give me any comments to
enlighten me? Thank you very much.

 

{{{

#

#         inheritance         inheritance

# object -------------> type -------------> Printable(Printable.__str__)

#   |                                           .

#   |                                           . instantiation

#   |                                           .

#   |                                           v

#    ----------------------------------------> C(?)

#                                               .

#                                               . instantiation

#                                               .

#                                               v

#                                              c(?)

#

>>> class Printable(type):

...   def __str__(cls):

...     return "This is class %s" % cls.__name__

...

>>> class C(object):

...   __metaclass__ = Printable

...

>>> print C                                       # equivalent to print
Printable.__str__(C)

This is class C

>>> c = C()

>>> print c                                       # equivalent to print
C.__str__(c)

<__main__.C object at 0x1870dacc>

 

>>> C.__str__

<slot wrapper '__str__' of 'object' objects>

>>> print C

This is class C

}}}

 

The question is why Printable.__str__ is invoked while executing "print C"
but "C.__str__" shows it is resolved as "objct.__str__"? 

 

Wish I can get reply from you. Really thanks.

 

Best Regards,


Tommy Zong
Chengdu Jiehua Technologies Co, Ltd.
Tel: 86-28-85148500-654
Mail:  <mailto:tzong at sigma-rt.com> tzong at sigma-rt.com
MSN:  <mailto:metalzong at 163.com> metalzong at 163.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20061130/be845502/attachment.html>


More information about the Python-list mailing list