A better way of making subsclassing of built-in types stick for attributes?

Ben Finney bignose+hates-spam at benfinney.id.au
Wed May 17 06:58:47 CEST 2006

"telesphore4 at gmail.com" <telesphore4 at gmail.com> writes:

> Is there a better way to make the subclassing of built-in types
> stick?

They stick. Your new classes are available until you get rid of them.

> The goal is to have the the fields of a class behave like strings
> with extra methods attached. That is, I want the fact that the
> fields are not strings to be invisible to the client
> programmers. But I always want the extras to be there for the
> clients too.
> What I'm doing is subclassing str.

Sounds like the right way to do what you're describing. Your subclass
can then be used to instantiate objects that behave like 'str'
objects, except for the different behaviour you define in your class.

> Of course, whenever you then set mystr = 'a string'

... you're instantiating a 'str' object, since that's what the syntax
you use will do.

> you loose the extra goodies that I have attached in the
> subclass.

Because you haven't created an object of that subclass.

    >>> class GroovyStr(str):
    ...     """ Our groovy extended string class """
    ...     pass
    >>> foo = "Larry"
    >>> bar = str("Curly")
    >>> baz = GroovyStr("Moe")
    >>> print [type(x) for x in foo, bar, baz]
    [<type 'str'>, <type 'str'>, <class '__main__.GroovyStr'>]

The syntax used to make the object assigned to 'foo' is just a
shortcut for the syntax used to assign to 'bar'. If you want to
instantiate anything else, you need to use that explicit syntax, such
as for the object assigned to 'baz'.

If you're hoping that "subclass" means "modify the behaviour of the
original class", you're mistaken. It makes a *new* class that has
behaviour *inherited from* the original class.

 \      "I stayed up all night playing poker with tarot cards. I got a |
  `\               full house and four people died."  -- Steven Wright |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list