passing variables as object attributes

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue Aug 17 12:42:00 CEST 2010


Vikas Mahajan a écrit :
> On 16 August 2010 19:23, Nitin Pawar <nitinpawar432 at gmail.com> wrote:
>> you would need to define a class first with its attiributes and then you may
>> want to initiate the variables by calling the class initilializer
>>
> Actually I have to dynamically add attributes to a object. I am
> writing python script for  FreeCAD software. I am using loop to create
> multiple cylinders and I am writing following code-:
> cyname = "Cylinder"
> FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname)
> FreeCAD.ActiveDocument.cyname.Radius= .5
> FreeCAD.ActiveDocument.cyname.Height= 10
> 
> And I am getting this error-:
> AttributeError: 'App.Document' object has no attribute 'cyname'

Indeed.

> But when I use Cylinder in place of cyname, I am not getting any error.

Of course.


> Please help.

I don't have FreeCAD installed, I won't install it, and I'm not going to 
read FreeCAD's doc neither, but you may want to check whether 
FreeCAD.ActiveDocument.addObject actually returns the newly created 
objet (which would be a sensible behaviour). If so, you'd just have to 
keep a ref to this object, ie:

cylinder = FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname)
cylinder.Radius = 0.5
# etc

Else, you can always get this ref using getattr, ie:

FreeCAD.ActiveDocument.addObject("Part::Cylinder",cyname)
cylinder = getattr(FreeCAD.ActiveDocument, cyname)
cylinder.Radius = 0.5
# etc

And while you're at it, you could save on both typing and execution time 
by keepin a ref to the document object itself:

doc = FreeCAD.ActiveDocument

for cyname in ("cylinder1, "cylinder2", "cylinderN"):
     doc.addObject("Part::Cylinder",cyname)
     cylinder = getattr(doc, cyname)
     cylinder.Radius = 0.5
     # etc

HTH



More information about the Python-list mailing list