Python 3 class returns 使用构造函数时为空

Python 3 class returns null when using contructor

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

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

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

您需要 explicit:

   self.model = desktop.getCurrentComponent()

__init__ 中的 model 变量是该方法的局部变量,不会附加到实例 self 除非您分配它。

当您在 class 下定义了 model,但在 __init__ 方法之外定义了一个 class attribute,它将在该 [=] 的所有实例中29=]。

否则,当您访问 myUno.model 时,您将面临 AttributeError

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

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