Home     My Faqts     Contributors     About     Help    

faqts : Computers : Programming : Languages : Python

FAQTs repaired & updated!
Thanks for your patience...
Entry Add Entry Alert - Edit this Entry

Did You Find This Entry Useful?

5 of 6 people (83%) answered Yes
Recently 5 of 6 people (83%) answered Yes

A newbie asks: Is is possible to use variables in a class name? ex. x=foo.bar.VARIABLE.method()

May 31st, 2002 23:03

Michael Chermside, Pete Farmer


Although there are multiple solutions, the best way to achieve this is
probably through the use of getattr().
Here is a sample senario where you might want to use the syntax you
describe:
Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class EmptyClass:
...     pass
...
>>> foo = EmptyClass()
>>> foo.bar = EmptyClass()
>>> class ClassWithMethod:
...     def method(self):
...             print 'executing method'
...
>>> foo.bar.baz = ClassWithMethod()
Now that we've set it up, here is what we would do to invoke the method:
>>> foo.bar.baz.method()
executing method
Okay, that works fine, but what if we had 'baz' as a string in a variable?
>>> fieldName = 'baz'
>>> foo.bar.fieldName.method()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: EmptyClass instance has no attribute 'fieldName'
That doesn't work because Python thinks you're trying to get at
bar.fieldName instead of bar.baz. This is where the getattr() function
comes in. Its purpose is to retrieve attributes when you have the name
as a STRING instead of a LITERAL:
>>> field = getattr(foo.bar, fieldName)
>>> field.method()
executing method
And if you need to ASSIGN values instead of READING them, there is a
corresponding setattr() function.



© 1999-2004 Synop Pty Ltd