Accessing class attribute

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Rafael Justo
    New Member
    • Mar 2007
    • 9

    Accessing class attribute

    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):

    Code:
    >>> class A:
    ...  x = 1
    ...  y = 2
    ...  z = 3
    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:
    Code:
    >>> print A."x"
      File "<stdin>", line 1
        print A."x"
                  ^
    SyntaxError: invalid syntax
    
    >>> A."y" = 4
      File "<stdin>", line 1
        A."y" = 4
            ^
    SyntaxError: invalid syntax
    Any clues? =)

    Best Regards!
    Rafael
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Use built-in function getattr().

    Code:
    >>> class A(object):
    ... 	x = 1
    ... 	y = 2
    ... 	z = 3
    ... 	
    >>> getattr(A, 'x')
    1
    >>>

    Comment

    • Rafael Justo
      New Member
      • Mar 2007
      • 9

      #3
      Thanks bvdet!

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

      Comment

      Working...