Getting a class attribute

Felix Thibault felixt at
Sat Mar 25 07:53:51 CET 2000

At 16:05 3/24/00 -0500, Alex wrote:
>> That lets you get access to "self", but at the cost of rewriting the
>> class method itself.
>Ouch, yeah that could be bad.  It would be nice if you could make a new
>version of the class, something like this:
>new_class = copy.copy (self.__class__)
>def new_degree_sin4 (self, deg, factor=(a*(math.pi/180)),
>                     sin=math.sin):
>    return sin (deg * factor)
>new_class.new_degree_sin4 = new_degree_sin4
>self.__class__ = new_class
>but it seems that classes aren't copy'able.  Plus, this has other
>problems with class members that you actually would like to be
>accessible to all instances.  Oh, well.

This works in my interpreter:

def newsubclass(inst, a):
    def degree_sin4(self, deg, factor=(a*math.pi/180), sin=math.sin):
        return sin(deg * factor)
    class Newsub(inst.__class__):
    Newsub.degree_sin4 = degree_sin4
    return Newsub

>>> class Empty:
>>> e = Empty()
>>> import math
>>> e.__class__ = newsubclass(e, 2)
>>> e.degree_sin4(45)
>>> e.degree_sin4
<method Newsub.degree_sin4 of Newsub instance at 8f8cd0>

More information about the Python-list mailing list