2017-04-04 107 views
0

我有類似下面的一些Python代碼:實例化一個全局對象

def a(): 
    x.b() 

def c(): 
    x = create_x() 
    a() 

這裏,x是一個對象,所以在c(),我想創建x,然後運行功能a()。我想x是全球性的,而不是必須將它作爲參數傳遞給a()。但是,如果我嘗試運行上面的代碼,它會告訴我,在a()不引用任何內容。

那麼標準的解決方案是什麼?一種想法是全局定義x並將其設置爲0:

x = 0 

def a(): 
    global x 
    x.b() 

def c(): 
    global x 
    x = create_x() 
    a() 

但這似乎有些奇怪,因爲它暗示x是一個整數,而實際上它是一個對象。

在C++中,我通常會通過創建一個指向x的指針,將其設置爲0,然後將指針設置爲由新對象x創建的內存來解決此問題。但是,Python中最好的解決方案是什麼?

+2

使用'None',而不是'0'? – Pit

+1

最初不要設置'x' ...?它將通過運行'c'來創建。你不必在函數之外聲明它,'global'已經做到了。 – deceze

+0

看看是否有幫助:http://stackoverflow.com/questions/16511321/python-global-object-variable – planet260

回答

0

這對我有效。在函數中啓動變量全局變量。

此代碼的問題是,必須先調用b。

def a(): 
    print(x) 

def b(): 
    global x 
    x = 1 
    a() 

b() 
0

我不知道是否回答這個問題,但它看起來像你需要調用global x只有內部c()功能。

class XClass: 
    def b(self): 
     print 'hello world' 

def create_x(): 
    return XClass() 

def a(): 
    x.b() 

def c(): 
    global x 
    x = create_x() 
    a() 

c() # hello world 
a() # hello world 

也許它,如果你創建create_x()方法裏面x變量減少混亂:

class XClass: 
    def b(self): 
     print 'hello world' 

def create_x(): 
    global x 
    x = XClass() 

def a(): 
    x.b() 

def c(): 
    create_x() 
    a() 

c() # hello world 
a() # hello world 
x.b() # hello world