How to change the superclass of an instance?

A

Alexander Stante

Hello,

I want to do the following. I have a function called display.set_mode()
which returns an instance of Surface. I want to add some bound
functions to this object therefore I thought to do something like:
.... def __new__(cls):
.... a = display.set_mode()
.... a.__class__ = screen
.... return a
.... def new_func(self):
.... pass

My idea was that my new created object has an attribute resolution
order of instance -> screen -> Surface and therefore I can use all
Surface methods on the instance and the new_func(). But I got the error
message: "TypeError: __class__ assignment: only for heap types"

I also tried to add a bound function (to the returned Surface of
display.set_mode()) with setattr and the appropriate arguments but I
got the error message: pygame.Surface object has no attribute 'update'
so I think Surface is somehow implemented immutable by intercepting
attribute access via __getattribute__

My question, how can I realize that I described above, because my
attempt seems to be wrong.

An other idea I had would be wrapping a class around the Surface
returned by display.set_mode() and then intercepting attribute
references with __getattr__ on that class and if not found in class or
instance, delegate them to the Surface. I think this way it would look
liked the wrapping class is a subclass of Surface. But Surface don't
have a __dict__ and I don't know an other way to call a function by his
name.

Bye
Alex
 
A

Alex Martelli

Alexander Stante said:
An other idea I had would be wrapping a class around the Surface
returned by display.set_mode() and then intercepting attribute
references with __getattr__ on that class and if not found in class or

Best (but, only attributes not found otherwise go to __getattr__, so, no
need for you to duplicate such checks).
instance, delegate them to the Surface. I think this way it would look
liked the wrapping class is a subclass of Surface. But Surface don't
have a __dict__ and I don't know an other way to call a function by his
name.

class generic_wrapper_base(object):
def __init__(self, wrappee): self.__dict__['_w'] = wrappee
def __getattr__(self, n): return getattr(self._w, n)
def __setattr__(self, n, v): setattr(self._w, n, v)
def __delattr__(self, n): delattr(self._w, n)

No need for the wrappee to have a __dict__: getattr, setattr and delattr
are the built-in functions you need. Happy wrapping!-)


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top