2013-07-24 81 views
0

讓我們考慮下面的腳本:的Python,使得在「稍微全球」範圍內定義的變量

def a(): 
    def b(): 
     smth = 3 
    print smth 

有什麼辦法,使在全球範圍內沒有定義的對象不便,但在雖然我們在b()函數中創建a()函數的範圍,但它的作用域是什麼?

喜歡的東西:

def a(): 
    def b(): 
     smth = 3 
     a_bit_more_global smth 
    print smth 

原因如下:

class Blabla(object): 
    def __init__(self,q,w) 
    self.q = q 
    self.w=w 
def a(): 
    def b(): 
     smth_2 = smth_1 + 1 
     global smth_2 
    smth_1 = 2 
    fen1 = Tk() 
    ... 
    ... 
    Button(...,command=b).grid() 
    my_blabla = Blabla(smth_1,smth_2) 
    return my_blabla 

我第一次不知道如何額外的參數傳遞給函數B()。我終於認爲我可以把b()放在一個()中。然後,同樣的問題,我想使用b()中創​​建的對象來創建對象my_blabla。你將如何處理這個問題?

我希望我的解釋有意義!他們呢?

謝謝!

+0

內部功能這是「範圍」。不,不是這樣,不是Python 2中的。 –

+0

全局變量(甚至是你所建議的)通常不是那麼好的編碼實踐,python更喜歡你通過參數和返回來傳遞所有東西。有沒有任何理由爲什麼你的腳本無法做到這一點?也許還有另一種解決方案 – scohe001

+0

喬希評論後我更新了我的帖子。 Thks –

回答

1

如約什說:

Deplace的類和存儲smth_2作爲self.smth_2

0

不在python中。你可以像它具有以下

def a(): 
    smth = [] 
    def b(): 
     smth = 3 
    if smth != []: 
     print smth 

因爲你開拓了廣泛,這將是難以修復潛在的bug的陣列我強烈地告誡這一點。我建議你b()函數返回任何東西,它會創建一個你需要在其他地方

def b(): 
    smth = 3 
    return smth 

如果你絕對必須做這樣的事我會考慮像C另一種語言++在那裏你可以分配smth動態

+1

在Python 3中,你可以使用'nonlocal'。 – kindall

2

你可以使用返回語句,例如

def a(): 
    def b(): 
     smth = 3 
     return smth 
    smth = b() 
    print smth 
+0

'b'作爲'command'參數傳遞給'Button'。它的返回值不可用。 ['方法內部的'self.smth'](http://stackoverflow.com/a/17842619/4279)可以用來代替。 – jfs

0

一個例子是等於一千答案:

def a(): 
    def b(): 
     smth = 3 
     return smth 
    smth = b() 
    print smth