简体   繁体   中英

Why doesn't imported class attribute change in Python?

I am trying to understand the mechanism of __import__(fromlist=['MyClass']) . Imagine I have several classes WhiteBox :

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

I am importing these classes with __import__(fromlist=['WhiteBox']) statement. I decide to repaint all boxes with the same color and create a loop:

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

When I try to access box.WhiteBox().color attribute, I still get None .

REPAINTED: WhiteBox None

I expected that __import__ would allow to manipulate the object as if it was instantiated, it appears not true. How do I solve this issue?

Use are using "use" as a property but it it defined as a function:

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

Next problem:

You are creating WhiteBox again and again so it will always have the initial None Value...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM