Paulo da Silva <[EMAIL PROTECTED]> 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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to