为什么在 Python 中导入的 class 属性没有变化?
Why doesn't imported class attribute change in Python?
我正在尝试了解 __import__(fromlist=['MyClass'])
的机制。
假设我有几个 类 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
我正在使用 __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__
将允许像实例化对象一样操作对象,但事实并非如此。我该如何解决这个问题?
使用 "use" 作为 属性 但它定义为函数:
box = box.WhiteBox() = "green"
#change it to:
box.WhiteBox().use("green")
下一题:
您一次又一次地创建 WhiteBox,因此它将始终具有初始 None 值...
box.WhiteBox().use("green") #created once
print("REPAINTED:", box.WhiteBox().name, box.WhiteBox().color) #two more times...
我正在尝试了解 __import__(fromlist=['MyClass'])
的机制。
假设我有几个 类 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
我正在使用 __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__
将允许像实例化对象一样操作对象,但事实并非如此。我该如何解决这个问题?
使用 "use" 作为 属性 但它定义为函数:
box = box.WhiteBox() = "green"
#change it to:
box.WhiteBox().use("green")
下一题:
您一次又一次地创建 WhiteBox,因此它将始终具有初始 None 值...
box.WhiteBox().use("green") #created once
print("REPAINTED:", box.WhiteBox().name, box.WhiteBox().color) #two more times...