extending objects (object-specific subclassing)

Peter Abel p-abel at t-online.de
Sat Jan 25 22:45:51 CET 2003

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()
overriding A.func() with fn()
>>> a.func=fn
>>> a.func()
overriding a.func() with class.method A.func()
>>> a.func=A().func
>>> a.func()
adding a new method nf()
>>> a.nf=new_func
>>> a.nf()
A new func()

More information about the Python-list mailing list