Класс Python 3 возвращает ноль при использовании 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>

Так что же случилось с этим в конструкторе? Разве это не должно быть там еще? Я пытаюсь избежать кода котельной плиты.

2 ответа

Решение

Я бы добавил к ответу Барроса, что вы объявляете 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()

Вы должны быть явными:

   self.model = desktop.getCurrentComponent()

model переменная внутри __init__ является локальным для этого метода и не будет привязан к экземпляру self если вы не назначите это.

Когда вы определили model прямо под классом, но вне __init__ метод, который вы определили class attribute, который будет во всех экземплярах этого класса.

Без этого, когда вы получили доступ myUno.model вы бы столкнулись с AttributeError,

Другие вопросы по тегам