繁体   English   中英

每次调用时创建一个新的python类副本

[英]creating a new copy of a python class each time it's called

我需要一些有关如何正确设置此设置的指导。 我有一个称为“属性块”的类,然后将使用它来创建3或4个“属性块”对象。 如下所示...

class AttributeBlock():
    def __init__(self, key, label, isClosed, isRequired, attributes):
        self.key = key
        self.label = label
        self.isClosed = isClosed
        self.isRequired = isRequired
        self.attributes = attributes if attributes is not None else {}

3个attributeBlock对象

AttributeBlock(
    key="Sphere",
    isRequired=True,
    attributes=[
        ''' Other class objects '''
        BoolProperty("ishidden", False, "Hidden"),
    ]
)

AttributeBlock(
    key="Box",
    isRequired=True,
    attributes=[
        ''' Other class objects '''
        BoolProperty("ishidden", True, "Hidden"),
    ]
)

AttributeBlock(
    key="Circle",
    isRequired=False,
    attributes=[
        ''' Other class objects '''
        BoolProperty("ishidden", True, "Hidden"),
    ]
)

然后,我想要做的就是能够将其中一个AttributeBlocks添加到一个对象,确保在添加对象时,它是AttributeBlock的新实例,因此其子属性对象是新实例。

这是我将添加属性块的对象。

class ToyBox():
    def __init__(self, name="", attributes=[]):
        self.name = name
        self.attributes = attributes[:]

newToyBox = ToyBox()
newToyBox.name = "Jimmy"

伪码

def add_attribute_block(toybox = None, key = "" ):
    if an AttributeBlock with the matching key exists:
        add it to toybox.attributes

add_attribute_block( newToyBox, "Box" )

print newToyBox
>>
ToyBox
name="Jimmy"
attributes=[
    AttributeBlock(
        key="Box",
        isRequired=True,
        attributes=[
            BoolProperty("ishidden", True, "Hidden"),
        ]
    ),
    AttributeBlock(
        key="Sphere",
        isRequired=True,
        attributes=[
            BoolProperty("ishidden", True, "Hidden"),
        ]
    )
]

如果要确保添加到ToyBox的Attribute实例是副本,最简单的方法是使用标准副本模块

import copy
...
class ToyBox(object):
    ...
    def add_attribute(self, attribute):
        self.attributes.append(copy.deepcopy(attribute))

如果要自动跟踪所有已创建的AttributeBlock对象,则可以使用类属性:

class AttributeBlock():
    objects = []
    def __init__(self, key, label, isClosed, isRequired, attributes):
        self.key = key
        self.label = label
        self.isClosed = isClosed
        self.isRequired = isRequired
        self.attributes = attributes if attributes is not None else {}
        self.objects.append(self)

一旦完成, add_attribute可能变为:

def add_attribute_block(toybox = None, key = "" ):
    if toybox is not None:
        for obj in AttributeBlock.objects:
            if obj.key == key:
                toybox.attributes.append(obj)
                break

您还可以使用映射而不是class属性的列表:

class AttributeBlock():
    objects = {]
    def __init__(self, key, label, isClosed, isRequired, attributes):
        if key in self.objects:
            # raise a custom exception
        ...
        self.objects[key] = self

然后,您可以简单地使用:

def add_attribute_block(toybox = None, key = "" ):
    if toybox is not None:
        if key in AttributeBlock.objects:
            toybox.attributes.append(AttributeBlock.objects[key])

如果要将列表对象的副本放置在ToyBox ,则必须更改创建方法以允许不将该副本放置在全局列表中。 在这种情况下,代码将变为:

class AttributeBlock():
    objects = {}
    dummy = {}
    def __init__(self, key, label, isClosed, isRequired,
             attributes, glob = None):
        if glob is None:
            glob = self.objects
        if key in glob:
            raise ValueError(str(key) + " already exists")
        self.key = key
        self.label = label
        self.isClosed = isClosed
        self.isRequired = isRequired
        self.attributes = attributes if attributes is not None else {}
        if glob is not self.dummy:
            glob[key] = self
    def copy(self):
        return AttributeBlock(self.key, self.label, self.isClosed,
                      self.isRequired, self.attributes[:],
                      self.dummy)

带有一个伪类对象(该伪类对象不允许将新创建的对象存储在任何容器中),以及一个可选的glob参数,该参数允许将其存储在外部字典中。 还要注意精确使用dummycopy方法。

add_attribute_block变为:

def add_attribute_block(toybox = None, key = "", glob = None ):
    if glob is None:
        glob = AttributeBlock.objects
    if toybox is not None:
        if key in glob:
            toybox.attributes.append(AttributeBlock.objects[key].copy())

使用copy方法存储在ToyBox中的是未存储在全局容器中的原始对象的副本。

如果我理解正确,您希望每个ToyBox实例包含AttributeBlock实例的列表,并检查列表中是否没有其他同名对象。

class AttributeBlock():
    def __init__(self, key): # demo, add the other parameters/attrs
        self.key = key
    def __str__(self):
        return self.key # add the other parameters/attrs

class ToyBox(object):
    def __init__(self):
        self.attributes = []

    def add_attr(self, a):
        gen = (attr for attr in self.attributes if attr.key == a.key)
        try:
            next(gen)
        except StopIteration:
            self.attributes.append(a)

    def __str__(self):
        return ','.join(map(str,self.attributes))

所以现在我们可以做

>>> toy = ToyBox()
>>> toy.add_attr(AttributeBlock("Box"))
>>> toy.add_attr(AttributeBlock("Sphere"))
>>> toy.add_attr(AttributeBlock("Box"))
>>> print toy
Box,Sphere

如您add_attribute ,使add_attribute函数成为add_attribute的实例方法是ToyBox

顺便说一句,如果attributes列表中的对象数量很大,最好使用字典:

class ToyBox(object):
    def __init__(self):
        self.attributes = dict()

    def add_attr(self, a):
        if a.key not in self.attributes:
            self.attributes[a.key] = a

    def __str__(self):
        return ','.join(map(str,self.attributes.values()))

注意:如果要保持对象添加的顺序,请改用OrderedDict

将所有属性块放入列表中。

blocks = []

// add your AttributeBlocks to this list
blocks.append(block1)
blocks.append(block2)
blocks.append(block3)

那很容易。

def add_attribute_block(toybox, key):
    #loop over list of blocks and find the block with that key
    for block in blocks:
        if block.key == key:
            #only add it to the toybox if its not already in there
            if not any(key in l.key for l in toybox.attributes):
                toybox.attributes.append(block)
                break

注意:

l.key for l in toybox.attributes是一个列表l.key for l in toybox.attributes并为您提供所有键的列表。

如果key在该列表中,则any(key in l.key for l in toybox.attributes)将返回True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM