Reputation: 13
Imagine having a class
class Bracings:
def __init__(self,type,axes,matrix):
self.type = type
self.axes = axes
self.matrix = matrix
class Element:
...
Then, imagine having
**elm** = *Element*()
**br** = *Bracings*( 'buckling' , 'y', [1,2,3,4] )
What I want to do is to create an attribute at elm
which will be like this
**elm**.bracing.buckling.y = **br**
the problem is i dont know the attributes names... it could be buckling
, it could be lateral_tortional
, it could be y
, it could be z
they take their values from the br object
How would you go about to solve this?
Upvotes: 1
Views: 173
Reputation: 398
first of all you have to create a new class which will be empty. then you have to set a function at Element like 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 )
Upvotes: 1
Reputation: 72
I think that you are trying to explore the inheritance concept. More information in the python documentation
Defining class Element as subclass of Bracing will allow you to access attributes of Bracing from Element.
class Element(Bracing):
Upvotes: 0