By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,715 Members | 748 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,715 IT Pros & Developers. It's quick & easy.

Accessing class attribute

Rafael Justo
P: 9
Hi,

I'm new in python development (NEWBIE). While I was using Cheetah Templates I got a problem about accessing template variables.

I have an object like this (class Template):

Expand|Select|Wrap|Line Numbers
  1. >>> class A:
  2. ...  x = 1
  3. ...  y = 2
  4. ...  z = 3
  5.  
But I'm just going to know the attributes names "on the fly". How can I set/get this attributes if I have just a string with the name of the attribute?

I know that I can't do this:
Expand|Select|Wrap|Line Numbers
  1. >>> print A."x"
  2.   File "<stdin>", line 1
  3.     print A."x"
  4.               ^
  5. SyntaxError: invalid syntax
  6.  
  7. >>> A."y" = 4
  8.   File "<stdin>", line 1
  9.     A."y" = 4
  10.         ^
  11. SyntaxError: invalid syntax
  12.  
Any clues? =)

Best Regards!
Rafael
Jul 2 '09 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Use built-in function getattr().

Expand|Select|Wrap|Line Numbers
  1. >>> class A(object):
  2. ...     x = 1
  3. ...     y = 2
  4. ...     z = 3
  5. ...     
  6. >>> getattr(A, 'x')
  7. 1
  8. >>> 
Jul 2 '09 #2

Rafael Justo
P: 9
Thanks bvdet!

The setattr method was perfect for me!
setattr(class, attribute, value)
Jul 2 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.