gpt4 book ai didi

Python 3 类在使用构造函数时返回 null

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:09 25 4
gpt4 key购买 nike

我使用以下命令启动了 Libre-Office Calc:

$ libreoffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"

import uno

# Class so I don't have to do this crap over and over again...
class UnoStruct():
localContext = None
resolver = None
ctx = None
smgr = None
desktop = None
model = None
def __init__(self ):
print("BEGIN: constructor")
# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()

# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )

# connect to the running office
ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
smgr = ctx.ServiceManager

# get the central desktop object
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)

# access the current writer document
model = desktop.getCurrentComponent()

print("END: constructor")

然后我调用它:

myUno = UnoStruct()
BEGIN: constructor
END: constructor

并尝试用

获取它
active_sheet = myUno.model.CurrentController.ActiveSheet

AttributeError: 'NoneType' object has no attribute 'CurrentController'

model 似乎是None (null)

>>> active_sheet = myUno.model
>>> print( myUno.model )
None
>>> print( myUno )
<__main__.UnoStruct object at 0x7faea8e06748>

那么它在构造函数中发生了什么?不应该还在吗?我试图避免样板代码。

最佳答案

我想在 Barros 的回答中补充一点,您将 localContext = None、resolver = None 等 声明为类变量。所以修改后的代码是这样的(如果你需要所有这些变量作为实例变量):

class UnoStruct():
def __init__(self ):
# get the uno component context from the PyUNO runtime
self.localContext = uno.getComponentContext()

# create the UnoUrlResolver
self.resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )

# connect to the running office
self.ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
self.smgr = ctx.ServiceManager

# get the central desktop object
self.desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)

# access the current writer document
self.model = desktop.getCurrentComponent()

关于Python 3 类在使用构造函数时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45332311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com