如何将Python中另一个类的属性值设置为attribute

2024-04-26 03:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

想象一下有一节课

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,也可以是lateral_tortional,也可以是y,也可以是z,它们的值来自对象

你打算怎么解决这个问题?你知道吗


Tags: brself属性initdeftypeelementmatrix
2条回答

我认为你是在尝试探索继承的概念。更多信息请参见python documentation

将类元素定义为支撑的子类将允许您从元素访问支撑的属性。你知道吗

class Element(Bracing):

首先,你必须创建一个新的类,它将是空的。然后你必须在元素上设置一个函数,比如设置括号:

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 )

相关问题 更多 >