Can print() be reloaded for a user defined class?

Benjamin Kaplan benjamin.kaplan at case.edu
Sun Sep 20 13:41:23 EDT 2009


On Sun, Sep 20, 2009 at 11:16 AM, Peng Yu <pengyu.ut at gmail.com> wrote:
> On Sun, Sep 20, 2009 at 9:19 AM, Dave Angel <davea at ieee.org> wrote:
>> Peng Yu wrote:
>>>
>>> <snip>
>>>>
>>>> you might use:
>>>>
>>>
>>> Is __repr__ =_str__ copy by reference or by value? If I change
>>> __str__ later on, will __repr__ be changed automatically?
>>>
>>> Regards,
>>> Peng
>>>
>>>
>>
>> Reference or value?  Neither one.  This assignment is no different than any
>> other attribute assignment in Python.  Technically, it binds the name
>> __repr__ to the function object already bound by __str__.  You now have a
>> second name pointing to the same object.  Rebinding one of those names  to
>> yet another different object won't affect the other name.
>>
>> name1 = "this is a test"
>> name2 = name1
>> name1 = "another string"           #this has no effect on name2
>>
>> print name1, name2
>
> I am more familiar with C++ than python. So I need to connect python
> concept to C++ concept so that I can understand it better.
>
> name1 and name are all references (in the C++ sense), right?
>
> __repr__  and __str__ are references (in the C++ sense) to functions
> and both of them could refer to the same function or two different
> ones, right?
>

Sort of, but it would be best to forget about the C++ ideas of
references and values because it will only confuse you. In python,
everything is an object and every attribute is stored as a dict key,
including functions. When you do __repr__ = __str__, you are making
the name '__repr__' refer to the same object as the name '__str__'.
Since they are the same object, any mutations made to one object will
appear in the other. However, a reassignment does not change the value
of the object, it just makes that key refer to another object. So if
you were to later change __str__ to a different method, __repr__
wouldn't change.

> Regards,
> Peng
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list