[C++-sig] contained structure access

David Abrahams dave at boost-consulting.com
Thu Nov 7 02:52:54 CET 2002


Graeme Lufkin <gwl at u.washington.edu> writes:

> 	Okay, I think I understand what's going on, and why
> return_internal_reference<> does what I want.  I used it, and it works. 
> But if the default behavior is to return a copy, why did the other
> access/assignments work.  That is, in the python code: 
>> >>> at = Atom()
>> >>> print at.x
>> 0.0
>> >>> at.x = 42
>> >>> print at.x
>> 42.0
>> >>> h = Holder()
>> >>> print h.a.x
>> 0.0
>> >>> h.a.x = 43
>> >>> print h.a.x
>> 0.0
>> >>> h.a = at
>> >>> print h.a.x
>> 42.0
> 	Why does 'at.x = 42' not also assign '42' to a temporary instance of
> the 'x' member variable?  And it's not just built-in types, the
> assignment of 'h.a = at' works, it doesn't assign 'at' to a temporary
> 'a'.  What am I missing?


Try it in Python to find out:

    >>> class X(object):
    ...     def get_x(self):
    ...             print 'in get_x'
    ...             return self.x
    ...     def set_x(self, n):
    ...             print 'in set_x(',n,')'
    ...             self.x = n
    ...     y = property(get_x,set_x)
    ...     def __init__(self):
    ...             self.x = 0
    ...
    >>> x = X()
    >>> x.y
    in get_x
    1
    >>> x.y = 1
    in set_x( 1 )

> 	Another, unrelated question: Can operator[] be overloaded to act the
> same in Python, that is like __getitem__ ?  

Yes.

> I tried
> 	.def("__getitem__", &MyClass::operator[])
> but it complained about sizeof() being applied to an unspecified
> type.

Can you show the complete error message?

> 	Even more: overloading *= for a float.  My class overloads *= for
> floats, and I'd like this to work in Python for integer and
> floating-point python types.  So I did
> 	.def(self *= float())
> similar to the tutorial example which uses int() instead.  Now I can do
> the *= in Python, but only on integers!  For example, I can do
> 	foo = MyClass()
> 	foo *= 2
> but when I try
> 	for *= 3.14
> I get a 'TypeError: can't apply sequence to non-int' or something like
> that.  Any thoughts?

This may be a Python bug, IIRC. Which version of Python are you using,
and can you try with a newer Python?

-- 
                    David Abrahams
dave at boost-consulting.com * http://www.boost-consulting.com





More information about the Cplusplus-sig mailing list