gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:28 24 4
gpt4 key购买 nike

想象一下上课

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 )

关于python - 如何在 Python 中将另一个类的属性值设置为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com