使用contructor时,Python 3类返回null

时间:2017-07-26 16:11:33

标签: python python-3.x libreoffice libreoffice-calc libreoffice-macros

我使用以下命令启动了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'

似乎modelNone(null)

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

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

2 个答案:

答案 0 :(得分:2)

您需要explicit

   self.model = desktop.getCurrentComponent()

model内的__init__变量是该方法的本地变量,除非您指定实例,否则不会附加到实例self

如果您在课程正确定义了model,但在__init__方法之外定义了class attribute,这将在该类的所有实例中。

如果没有,当您访问myUno.model时,您将面临AttributeError

答案 1 :(得分:2)

我想在Barros的答案中添加localContext = None, resolver = None, etc.作为类变量。所以修改后的代码是这样的(如果你需要所有这些变量作为实例变量):

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()