我正在使用win32com从Python控制Visio。
获取和设置shapeheet值非常简单:
print(shp.CellsU('PinX').ResultStr(''))
# and
shp.CellsU('PinX').FormulaU = '1'
到目前为止一切都那么好,但我希望通过覆盖setter和getter来获得更短的语法:
print(shp.PinX)
# and
shp.PinX = '1'
所以我去了一个房产:
ShapeClass = type(shp)
def SetPinX(self,value):
self.CellsU('PinX').FormulaU = value
def GetPinX(self):
return self.CellsU('PinX').ResultStr('')
ShapeClass.PinX = property(GetPinX,SetPinX)
现在奇怪的结果 - getter工作正常(print(shp.PinX)给出预期值),但setter不起作用。
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\conda\conda\envs\YG_Package_1\lib\site-packages\win32com\client\__init__.py in __setattr__(self, attr, value)
478 try:
--> 479 args, defArgs=self._prop_map_put_[attr]
480 except KeyError:
KeyError: 'PinX'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
<ipython-input-28-23f68b65624d> in <module>()
----> 1 shp.PinX= '1'
~\AppData\Local\conda\conda\envs\YG_Package_1\lib\site-packages\win32com\client\__init__.py in __setattr__(self, attr, value)
479 args, defArgs=self._prop_map_put_[attr]
480 except KeyError:
--> 481 raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
482 self._oleobj_.Invoke(*(args + (value,) + defArgs))
483 def _get_good_single_object_(self, obj, obUserName=None, resultCLSID=None):
AttributeError: '<win32com.gen_py.Microsoft Visio 15.0 Type Library.IVShape instance at 0x85710888>' object has no attribute 'PinX'
dir(ShapeClass)显示属性PinX就好了。
使用自己的类进行测试也有效。所以错误不是我正在实现属性的方式。
我怀疑win32com遇到了被覆盖的setter问题。
有人会对如何解决这个问题有所了解吗?
win32com.client.DispatchBaseClass
基类使用__setattr__
拦截所有属性设置访问。这会影响您的属性对象;属性设置器仅由默认的object.__setattr__
实现调用,而不是由win32com
使用的自定义方法调用。
所以是的,shp.PinX = '1'
将调用DispatchBaseClass.__setattr__('PinX', '1')
,即使在类上定义了一个名为PinX
的数据描述符,并且因为它只支持COM接口定义的属性而失败。
您必须在此处覆盖__setattr__
方法以首先检查可用属性。您可以子类化DispatchBaseClass
或特定生成的类,或者我们可以直接修补win32com
:
import inspect
from win32com.client import DispatchBaseClass
dispatch_setattr = DispatchBaseClass.__setattr__
def allow_datadescriptor_setattr(self, name, value):
# for non-private names, check if the attribute exists on the class
# and is a data descriptor. If so, use object.__setattr__ to permit
# the data descriptor to intercept attribute setting
if name[:1] != '_' and inspect.isdatadescriptor(getattr(type(self), name, None)):
return object.__setattr__(self, name, value)
# private name, or doesn't exist on the class, or not a data descriptor
# invoke the original win32com dispatch __setattr__
dispatch_setattr(self, name, value)
DispatchBaseClass.__setattr__ = allow_datadescriptor_setattr
以上允许任何descriptor with a __set__
or __delete__
method拦截其名称的赋值,而不仅仅是property
对象。
您正在混合.Formula和.ResultStr方法。一个细胞可以有:
.Formula .FormulaU .Result .ResultU .ResultStr .ResultStrU .FormulaForce.FormulaForceU
在您的代码中,您使用.ResultStr获取单元格内容,并使用.FormulaU来设置单元格。我建议您查看Visio API以查看所有这些之间的差异。如果单元格具有受保护的公式/值,则需要使用.FormulaForce方法。