[英]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__
允许操纵对象,就像它被实例化一样,看起来不是真的。 我该如何解决这个问题?
使用“使用”作为属性,但它定义为一个函数:
box = box.WhiteBox() = "green"
#change it to:
box.WhiteBox().use("green")
下一个问题:
您一次又一次地创建WhiteBox,因此它将始终具有初始无值...
box.WhiteBox().use("green") #created once
print("REPAINTED:", box.WhiteBox().name, box.WhiteBox().color) #two more times...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.