Suggesting for overloading the assign operator

John Roth johnroth at ameritech.net
Tue Jul 1 17:17:01 EDT 2003


"John Roth" <johnroth at ameritech.net> wrote in message
news:vg3eghr5kj1sd8 at news.supernews.com...
>
> "Rim" <rimbalaya at yahoo.com> wrote in message
> news:6f03c4a5.0306301931.3f15fbb7 at posting.google.com...
> > Hi,
> >
> > I have been thinking about how to overload the assign operation '='.
> > In many cases, I wanted to provide users of my packages a natural
> > interface to the extended built-in types I created for them, but the
> > assign operator is always forcing them to "type cast" or coerce the
> > result when they do a simple assign for the purpose of setting the
> > value of a variable.
>
> Use a property. Changing the semantics of the assignment
> statement (NOT assignment operator) is not going to happen.
>
> Properties are new in Python 2.2 (which is around a year
> old by now.) They enable you to have getter and setter
> methods with an interface that looks like an instance
> variable.
>
> John Roth

I usually don't reply to my own posts, but I thought it
might be nice if I put up a skeletal example of how to do it.

I'm assuming that what you want is a way of insuring, in a
class named Foo, that the variable fooBar is always bound
to a class instance of Bar, regardless of what the user tries
to assign to it.

Most of what follows is documented in "What's New in Python 2.2,"
section 2: Peps 252 and 253: Type and Class Changes.

The information on the __new__ method is in the document
under 2.5: Related Links.

The way to do this is:

1. Both Foo and Bar have to inherit from a built-in type.
That's usually "object", but it can be any built-in type.

2. Refactor Foo so that all references to self.fooBar
now refer to self._fooBar. (It can be any name; the
underscore is a convention that means "private."

3. Insert the following code in Foo:

def _getFooBar(self):
    return self._fooBar

def _setFooBar(self, parm):
    self._fooBar = Bar(parm)

_fooBar = property(_setFooBar, _getFoobar, None, "doc strings swing")

4. In class Bar, use the __new__ method to check if
the parameter is an instance of class Bar. If it is, return that
instance, otherwise call your superclass's __new__ method
to create a  new object and return it.

5. In class Bar, do whatever type determination you need to
in the __init__ method to build your new Bar object.

Most of this is documented in "What's New in Python 2.2,"
section 2: Peps 252 and 253: Type and Class Changes.

The information on the __new__ method is in the document
under 2.5: Related Links.

HTH

John Roth

>
>






More information about the Python-list mailing list