2016-01-09 38 views
1

我想了解__import__(fromlist=['MyClass'])的機制。 想象我有幾類WhiteBox爲什麼Python中不導入類屬性更改?

class WhiteBox: 
    def __init__(self): 
     self.name = "White Box" 
     self.color = None 

    def use(self, color): 
     self.paint(color) 

    def paint(self, color): 
     self.color = color 

我進口這些__import__(fromlist=['WhiteBox'])聲明。 我決定重新繪製所有箱子用相同的顏色,並創建一個循環:

for box in imported_boxes: 
    box.WhiteBox().use = "green" 
    print("REPAINTED:", box.WhiteBox().name, box.WhiteBox().color) 

當我嘗試訪問box.WhiteBox().color屬性,我仍然得到None

REPAINTED: WhiteBox None 

我預計__import__將使操縱的對象,就好像它被實例化,看來並非如此。我該如何解決這個問題?

+1

我想你應該加上'self.color = None'成'__init__'功能 – Arman

+0

對不起,太快了,OK。如果我添加'self.color = None',該屬性將保持爲'None'。 – minerals

+0

當你調用'box.WhiteBox()。use =「green」'時它應該改變,不是嗎? – Arman

回答

3

使用使用「使用」的屬性,但它它定義爲一個函數:

box = box.WhiteBox() = "green" 
#change it to: 
box.WhiteBox().use("green") 

下一個問題是:

你一次又一次地創造白盒測試所以它總是擁有初始無值...

box.WhiteBox().use("green") #created once 
print("REPAINTED:", box.WhiteBox().name, box.WhiteBox().color) #two more times... 
相關問題