相关疑难解决方法(0)

为什么属性引用与Python继承一样?

以下看起来很奇怪..基本上,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) - 但什么时候这种行为是可取的?

python inheritance class

19
推荐指数
2
解决办法
7805
查看次数

为什么这些列表相同?

我无法理解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)

python

1
推荐指数
1
解决办法
148
查看次数

标签 统计

python ×2

class ×1

inheritance ×1