想象一下上课
class Bracings:
def __init__(self,type,axes,matrix):
self.type = type
self.axes = axes
self.matrix = matrix
class Element:
...
然后,想象一下
**elm** = *Element*()
**br** = *Bracings*( 'buckling' , 'y', [1,2,3,4] )
我想要做的是在elm
处创建一个像这样的属性
**elm**.bracing.buckling.y = **br**
问题是我不知道属性名称...它可能是buckling
,它可能是later_tortional
,它可能是y
,可能是 z
他们从 br 对象获取值
您将如何解决这个问题?
首先,您必须创建一个空的新类。那么你必须在 Element 上设置一个函数,如 set_bracings:
class Empty(object):
def __init__(self):
pass
#then at class Element:
class Element:
....
def set_bracings(self, bracing):
case = bracing.case
axes = bracing.axes
if hasattr(self,'bracings') == False:
#Its the first ever bracing which is created
empty1 = Empty()
setattr( empty1, axes, bracing)
empty2 = Empty()
setattr( empty2, case, empty1)
setattr( self, 'bracings', empty2)
else:
if hasattr(self.bracings,case) == False:
#if we enter in this check then at some point another attribute of case was created, so we keep it
brace = self.bracings
empty1 = Empty()
setattr( empty1, axes, bracing)
setattr( brace, case, empty1)
setattr( self, 'bracings', brace)
else:
#If we enter here then we our 'case' is the same as another 'case' that was created earlier so we have to keep it
brace = self.bracings
old_axes = getattr(self.bracings , case)
setattr( old_axes, axes, bracing)
setattr( brace, case, old_axes)
setattr( self, 'bracings', brace)
#after that you only have to do
elm.set_bracings( br )
我是一名优秀的程序员,十分优秀!