getattr/setattr q.

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Apr 3 01:02:10 EDT 2007


Paulo da Silva <psdasilvaX at esotericaX.ptX> writes:

> In a class C, I may do setattr(C,'x',10).

That would set an attribute on the class C, shared by all instances of
that class.

If you want to set an attribute on an instance, you need to do so on
the instance object::

    >>> class Foo(object):
    ...     def __init__(self):
    ...             setattr(self, 'bar', 10)
    ...
    >>> Foo.bar
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    AttributeError: type object 'Foo' has no attribute 'bar'
    >>> spam = Foo()
    >>> spam.bar
    10

> Is it possible to use getattr/setattr for variables not inside
> classes or something equivalent? I mean with the same result as
> exec("x=10").

"Variables not inside classes or functions" are attributes of the
module (so-called "global" attributes). Thus, you can use setattr on
the module object::

    >>> import sys

    >>> def foo():
    ...     this_module = sys.modules[__name__]
    ...     setattr(this_module, 'bar', 10)
    ...
    >>> bar
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    NameError: name 'bar' is not defined
    >>> foo()
    >>> bar
    10

-- 
 \         "I'm beginning to think that life is just one long Yoko Ono |
  `\   album; no rhyme or reason, just a lot of incoherent shrieks and |
_o__)                                   then it's over."  -- Ian Wolff |
Ben Finney



More information about the Python-list mailing list