Python 嵌套对象存储在字典中的问题
我在运行时更改类的值然后将其实例化为对象,然后将该对象存储在另一个类中并将其放入 python 字典中时遇到了一些麻烦。
这是我为了说明问题而编写的一个小代码片段:
import unittest
class cls1(object):
def __init__(self, obj):
self.obj = obj
class cls2(object):
def __init__(self):
self.var = 1
class Testdict(unittest.TestCase):
def __init__(self):
self.objs = dict()
def runTest(self):
obj2 = cls2()
obj1 = cls1(cls2())
self.objs["test1"] = obj1
self.assertEqual(self.objs["test1"].obj.var, 1)
cls2.var = 2
self.assertEqual(cls2.var, 2)
obj1 = cls1(cls2())
self.objs["test2"] = obj1
self.assertEqual(self.objs["test1"].obj.var, 1)
self.assertEqual(self.objs["test2"].obj.var, 2)
if __name__ == "__main__":
d = Testdict()
d.runTest()
Why would cls2 not instantiate with getting it's var equal to 2?
我希望这个问题有一定道理。
I'm having some trouble with changing the value of a class at runtime and then instantiating it into an object, then storing that object inside of another class and putting that into python dictionary.
Here is a small code snippet I wrote to illustrate the problem:
import unittest
class cls1(object):
def __init__(self, obj):
self.obj = obj
class cls2(object):
def __init__(self):
self.var = 1
class Testdict(unittest.TestCase):
def __init__(self):
self.objs = dict()
def runTest(self):
obj2 = cls2()
obj1 = cls1(cls2())
self.objs["test1"] = obj1
self.assertEqual(self.objs["test1"].obj.var, 1)
cls2.var = 2
self.assertEqual(cls2.var, 2)
obj1 = cls1(cls2())
self.objs["test2"] = obj1
self.assertEqual(self.objs["test1"].obj.var, 1)
self.assertEqual(self.objs["test2"].obj.var, 2)
if __name__ == "__main__":
d = Testdict()
d.runTest()
Why would cls2 not instantiate with having it's var equal to 2?
I hope this question makes some sense.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你所展示的内容是行不通的。曾经。
这是一个实例变量。它不是一个类变量。您无法使用
Cls2.var
访问该.var
该变量仅存在于该类的每个唯一实例中。不更改 self.var 实例变量。这会在 Cls2 类中创建一个新的类变量。
你需要做这样的事情。
现在你可以做
任何你正在做的事情的其余部分都应该有效。
What you're showing can't work. Ever.
That's an instance variable. It's not a class variable. You can't access that
.var
withCls2.var
That variable only exists within each unique instance of the class.Does not change the
self.var
instance variable. That creates a new class variable in theCls2
class.You'd need to do something like this.
Now you can do
And the rest of whatever it is you're doing should work.
如果 cls2 在实例化时没有覆盖 cls.var,则您的测试将有效。
试试这个:
try
语句只是检查您是否已经设置了var
。Your test would work if cls2 didn't overwrite cls.var when it is instantiated.
Try this:
The
try
statement just checks to see if you've already setvar
.