以下看起来很奇怪..基本上,somedata属性似乎在所有继承的类之间共享the_base_class.
class the_base_class:
somedata = {}
somedata['was_false_in_base'] = False
class subclassthing(the_base_class):
def __init__(self):
print self.somedata
first = subclassthing()
{'was_false_in_base': False}
first.somedata['was_false_in_base'] = True
second = subclassthing()
{'was_false_in_base': True}
>>> del first
>>> del second
>>> third = subclassthing()
{'was_false_in_base': True}
Run Code Online (Sandbox Code Playgroud)
self.somedata在__init__函数中定义显然是解决这个问题的正确方法(所以每个类都有它自己的somedatadict) - 但什么时候这种行为是可取的?
我无法理解x和y是如何相同的列表.我一直在尝试使用print语句进行调试并import code; code.interact(local=locals())进入各个点,但我无法弄清楚究竟是怎么回事:-(
from collections import namedtuple, OrderedDict
coordinates_2d=["x","y"]
def virtual_container(virtual_container, objects_type):
"""Used to create a virtual object given a the type of container and what it holds.
The object_type needs to only have normal values."""
if issubclass(virtual_container, list):
class my_virtual_container_class:
"""This singleton class represents the container"""
def __init__(self):
#Define the default values
__vals__=OrderedDict([(key,list()) for key in objects_type])
print(id(__vals__["x"]), id(__vals__["y"]))#ids are different: 12911896 12911968
#Then functions to access them
d={key: lambda self: self.__vals__[key] for key in objects_type}
d["__vals__"]=__vals__ …Run Code Online (Sandbox Code Playgroud)