[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Surface objects





On Thu, Jul 14, 2011 at 10:05 AM, DR0ID <dr0id@xxxxxxxxxx> wrote:
On 14.07.2011 16:18, sam.hacking@xxxxxxxx wrote:
Hey guys,
 
I have a class which inherits from pygame.Surface. If the class gets created with a tuple, I create a new surface by calling pygame.Surface.__init__, so my class will work as a pygame.Surface object.
     I also need this class to be created with existing pygame.Surface objects. So, if I pass in a pygame.Surface object to my class, how can I get my class to be treated as a pygame.Surface object? Do pygame.Surface objects store their data in an accessible variable such as _image, in which case I presume I could copy the Surface._image to self._image to get the desired effect?
 
Thanks,
Sam Bull


Hi

An old experiment of mine, it might give you a clue how you can do it (actually it replaces the pygame Surface object with the SurfaceObject class):

https://python-pyknic.googlecode.com/svn/branches/pyknic-2.0/experimental/surfaceobject.py


Hope it helps.

~DR0ID

Hi Sam,

If all you need is access to pygame.Surface's methods and data (and not type info like issubclass() or isinstance()) I would recommend against inheriting from a library class (especially one written in Python's C API, as I suspect pygame.Surface is) and instead use this hack:

# Python 2.x code
class MySurface(object):
    def __init__(self, obj):
        if isinstance(obj, tuple):
            self._surf = pygame.Surface(*tuple)
        elif isinstance(obj, pygame.Surface):
            self._surf = obj
    def __getattr__(self, attr):
        return getattr(self._surf, attr)

The __getattr__ method is invoked whenever an instance field isn't found the usual way. So, if you have a MySurface object called "s", this wouldn't invoke __getattr__:

assert s.__init__

But this would:

assert s.convert

And calling s.convert() would still function as normal, because its self parameter is actually bound to s._surf.

Hope that helps,

--
Michael