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

时间:2015-10-24 20:39:43

标签: python class attributes

想象一下班级

CITY

然后,假设有

Bedrooms

我想要做的是在Bathsroom创建一个属性,就像这样

for($z=1; $z < $num_records; $z++)

问题是我不知道属性名称......它可以是$num_records=count($columns); for($z=0; $z <= $num_records; $z++){ $rowData=fetchData($columns[$z] ,$columns[$z],1); fputcsv($fp, $rowData); } ,可以是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他们从 br 对象

中获取值

你将如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

首先,您必须创建一个空的新类。那么你必须在元素中设置一个函数,如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 )

答案 1 :(得分:0)

我认为您正在尝试探索继承概念。 python documentation

中的更多信息

将类Element定义为Bracing的子类将允许您从Element访问Bracing的属性。

class Element(Bracing):