0
當空

我開始自由報辦公計算器使用以下命令:的Python 3類返回使用構造器

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

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

那麼在構造函數中發生了什麼?它不應該仍然在那裏嗎?我試圖避免鍋爐板代碼。

+0

P.S.我知道它實際上並不是一個結構體,我只是稱它爲結構體。 – leeand00

+0

您從未設置'myUno.model',所以它仍然是類的定義中的'None'。 – kindall

+0

[此github代碼]中的'UnoObjs'類(https://github.com/silnrsi/libreoffice-linguistic-tools/blob/master/LinguisticTools/pythonpath/lingt/utils/util.py)執行此操作。 –

回答

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

那麼'self'就像Java中的this一樣呢? – leeand00

+1

@ leeand00是的。不同之處在於'self'不是一個關鍵字(只是一個常規的名稱):你可以用'obj','this'來代替它,因爲參數是顯式的(這對於沒有被設計爲最初面向對象)。 –

+0

對,因爲它是一個參數,所以你可以自己命名。但是如果你想讓另一個Python編碼器輕鬆讀取它,最好堅持'self'約定。 – leeand00

2

你需要explicit

self.model = desktop.getCurrentComponent() 

model變量中__init__是局部的方法,除非你指定它不會被附加到實例self

當你正確的類定義下model,但__init__方法外,你定義的class attribute,這將是該類別的所有實例。

沒有這個,當你訪問myUno.model時,你會面對一個AttributeError