'Wrapping an object in Python
I am currently trying to write a python wrapper for a project that use non native python calls, to be able to run it in native python.
The code is normally ran into a software that expose additionals non native objects and function that can be used in the python code. I am using win32com.client to connect to the software to retrieve its non native objects and functions, and expose them in my native python code.
As I cannot change change the source code, with it's custom calls to the software, I am trying to write a wrapper.
I have a piece of code that looks like this:
Variable.VariableByName["myVariableName"] = myVariableValue
This code is supposed to edit the attribute myVariableName of the object Variable and set it to myVariableValue. VariableByName, in native python, is seen as a function, and cannot be called via "VariableByName["myVariableName"]".
I have created this wrapper, but I cannot figure how to retrieve the myVariableName and the myVariableValue in the wrapper...
class VariableWrap():
def __init__(self, object):
global _VariableWrap
_VariableWrap = object
def __getattribute__(self, l_attribute):
global _VariableWrap
if l_attribute in ["VariableByName"]:
_VariableWrap.__setattr__( VariableName?, VariableValue?)
return ?
return _VariableWrap.__getattr__(l_attribute)
Variable = VariableWrap(Variable)
Thanks in advance for any help
Solution 1:[1]
Your notation V['key'] is handled by __getitem__ and __setitem__, also, instead of having a global variable is better to hold a reference of the object by instance, so that you can use the same wrapper to wrap different objects.
class VariableWrap():
def __init__(self, variables):
self._variables = variables
def __getitem__(self, l_attribute):
if l_attribute in ["VariableByName"]:
return getattr(self._variables,l_attribute)
def __setitem__(self, l_attribute, value):
if l_attribute in ["VariableByName"]:
setattr(self._variables, l_attribute, value)
# The real object where the variables will be stored
class Object(object):
VariableByName = 'default'
variables = Object()
wrap = VariableWrap(variables)
# Get directly
assert(variables.VariableByName == 'default')
# Get by the wrapper
assert(wrap['VariableByName'] == 'default')
# Modify object directly and have it reflected in the wrapper
variables.VariableByName = 1
assert(variables.VariableByName == 1)
assert(wrap['VariableByName'] == 1)
# Modify by the wrapper and have it reflected in the wrapped object
wrap['VariableByName'] = 2
assert(variables.VariableByName == 2)
assert(wrap['VariableByName'] == 2)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bob |
