Connecting Tech Pros Worldwide Help | Site Map

Accessing class attribute

  #1  
Old July 2nd, 2009, 04:28 PM
Newbie
 
Join Date: Mar 2007
Location: São Paulo - Brazil
Posts: 4
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
  #2  
Old July 2nd, 2009, 04:38 PM
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,545

re: Accessing class attribute


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. >>> 
  #3  
Old July 2nd, 2009, 04:43 PM
Newbie
 
Join Date: Mar 2007
Location: São Paulo - Brazil
Posts: 4

re: Accessing class attribute


Thanks bvdet!

The setattr method was perfect for me!
setattr(class, attribute, value)
Reply

Tags
access, attributes, cheetah, python, template


Similar Threads
Thread Thread Starter Forum Replies Last Post
ClassName.attribute vs self.__class__.attribute Gabriel Rossetti answers 18 June 27th, 2008 05:28 PM
Accessing Class rockoyster answers 3 July 21st, 2005 01:59 AM
Implementing class attribute access methods via pseudo-function overloading. Doran_Dermot@emc.com answers 7 July 18th, 2005 05:56 PM
Accessing class members from C disgracelands answers 2 July 18th, 2005 03:11 AM