我需要一些关于如何正确设置我要做的事情的指导。 我有一个名为Attribute Block的类,然后用它创建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"),
]
)
然后我想做的是能够将这些AttributeBlock中的一个添加到一个对象中,确保在添加时,它是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"),
]
)
]
将所有属性块放在一个列表中。你知道吗
那就容易了。你知道吗
注:
l.key for l in toybox.attributes
是一个列表,它提供了所有键的列表。你知道吗any(key in l.key for l in toybox.attributes)
如果key
在该列表中,则返回True
。你知道吗如果要确保添加到ToyBox的属性实例是副本,最简单的方法是使用standard copy module
如果要自动跟踪所有创建的
AttributeBlock
对象,可以使用class属性:一旦这样做,
add_attribute
可能会变成:也可以使用映射而不是类属性的列表:
然后您可以简单地使用:
如果要将列表对象的副本放入
ToyBox
,则必须更改创建方法以允许不将该副本放入全局列表。在这种情况下,代码将变成:一个虚拟类对象允许不在任何容器中存储新创建的对象,一个可选的
glob
参数允许将其存储在外部dict中。你知道吗add_attribute_block
变成:使用copy方法在ToyBox中存储未存储在全局容器中的原始对象的副本。你知道吗
相关问题 更多 >
编程相关推荐