extending objects (object-specific subclassing)
Peter Abel
p-abel at t-online.de
Sun Jan 26 16:55:15 EST 2003
p-abel at t-online.de (Peter Abel) wrote in message news:<13a533e8.0301251345.4118ad15 at posting.google.com>...
> David Garamond <davegaramond at icqmail.com> wrote in message news:<mailman.1043501925.18338.python-list at python.org>...
> > in ruby you can "subclass an object". that is, you override and/or add
> > methods specific to an object, not for the entire class. an example below:
> >
> > a = "hello"
> > b = a.dup # b becomes another String object with the value of "hello"
> >
> > def b.to_s
> > "The value is '#{self}'"
> > end
> >
> > puts a.to_s # hello
> > puts b.to_s # The value is 'hello'
> >
> > behind the scene, ruby creates a new class just for the object a. the
> > original a's class, String, will be the new class' superclass. ruby
> > hides this, though, so you'll still see a as being the String object.
> >
> > puts a.class # String
> > puts b.class # String
> >
> > i wonder if python has a similar concept. or how do we do something
> > roughly similar in python.
>
> I never heard about subclassing objects in python.
> But method-overriding and -adding is possible:
> >>> class A:
> ... def func(self):
> ... print 'classA.func()'
> ...
> >>> def fn():
> ... print 'instance.func()'
> ...
> >>> def new_func():
> ... print 'A new func()'
> ...
> >>> a=A()
> >>> a.func()
> classA.func()
> overriding A.func() with fn()
> >>> a.func=fn
> >>> a.func()
> instance.func()
> overriding a.func() with class.method A.func()
> >>> a.func=A().func
> >>> a.func()
> classA.func()
> adding a new method nf()
> >>> a.nf=new_func
> >>> a.nf()
> A new func()
> >>>
> Regards
> Peter
Forget, what I wrote here.
Python made me believe it would work.
It will only override an object-method with
a function. But from this function you can't
access to object's attributes.
Now I understand the difference for myself.
For correct information see thread:
"Replacing methods without subclassing"
at comp.lang.python.
Sorry
Peter
More information about the Python-list
mailing list