Python factory property or handle class for wrapping an external library

I am writing a Python shell class for the C # API, accessed through Pythonnet. Since I want to extend the API with my own methods, I decided to wrap it using the compositional approach indicated here :

The C # API makes heavy use of the properties that I want to simulate in my Python code. The following minimal example shows my current approach for an example of a C # Surface class with two width and height properties:

class MySurface:
    def __init__(api_surface):
        self.api_surface = api_surface

    @property
    def width(self):
        return self.api_surface.width

    @width.setter
    def width(self, value):
        self.api_surface.width = value

    @property
    def height(self):
        return self.api_surface.height

    @height.setter
    def height(self, value):
        self.api_surface.height = value

, 50 . , .. , , - , . factory . !

: python, . {hit tab} surface.width surface.height. getattr, .

+4
2

, factory:

def surface_property(api_property_name, docstring=None):
    def getter(self):
        return self.api_surface.__getattribute__(api_property_name)

    def setter(self, value):
        self.api_surface.__setattr__(api_property_name, value)

    return property(getter, setter, doc=docstring)

:

class MySurface:
    def __init__(api_surface):
        self.api_surface = api_surface

    width = surface_property('Width','Get and set the width.')
    height = surface_property('height', 'Get and set the height.')
+3

getattr setattr, . python2 btw.

class MySurface(object):
    def __init__(self):
        self.props = {"width": 0, "length": 0, ...}

    def __setattr__(self, attr, val):
        if attr in self.props:
            self.props[attr] = val
        else:
            super(MySurface, self).__setattr__(attr, val)

    def __getattr__(self, attr):
        if attr in self.props:
           return self.props[attr]
        else:
           return self.__getattribute__(attr)
+1

All Articles