Mailing List Archive

Assign a value to a var content in an object
Hello!

Is there a better way of doing this?
Why didn't setattr (as commented) work?

Thanks for an help/comments.

class C:
def f(self,v):
#setattr(self,n,v)
self.__dict__['n']=v

c=C()
c.f(3)
print(c.n)

--
https://mail.python.org/mailman/listinfo/python-list
Re: Assign a value to a var content in an object [ In reply to ]
Às 23:28 de 10/10/21, Stefan Ram escreveu:
> Paulo da Silva <p_d_a_s_i_l_v_a_ns@nonetnoaddress.pt> writes:
>> class C:
>> def f(self,v):
>> #setattr(self,n,v)
>> self.__dict__['n']=v
>
>> Why didn't setattr (as commented) work?
>
> Because the name n has not been initialized to a suitable
> value in the function f. You could write
>
> setattr( self, "n", v )
Ah, OK - I missed the "" around n! :-(
>
> , but if you want this,
>
> self.n = v
>
> would be better.
Of course :-)
But that's not the purpose. This is just a toy example.

Thanks.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Assign a value to a var content in an object [ In reply to ]
On Tue, Oct 12, 2021 at 9:03 AM Paulo da Silva
<p_d_a_s_i_l_v_a_ns@nonetnoaddress.pt> wrote:
>
> Hello!
>
> Is there a better way of doing this?
> Why didn't setattr (as commented) work?
>
> Thanks for an help/comments.
>
> class C:
> def f(self,v):
> #setattr(self,n,v)
> self.__dict__['n']=v
>
> c=C()
> c.f(3)
> print(c.n)
>

Because setattr needs a string, just like the assignment to the
dictionary does. Try:

setattr(self, "n", v)

Or, since it's a constant:

self.n = v

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list