Note that there are some explanatory texts on larger screens.

plurals
  1. POSetting a property inside a Python method
    text
    copied!<p>I want to set a read-only attribute inside a class method.<br> I have already tried this:</p> <pre><code>class Foo(object): def __init__(self, v): self._set('_v', v) def _set(self, attr, v): setattr(self, attr, v) setattr(Foo, attr[1:], property(lambda self: getattr(self, attr))) </code></pre> <p>but it is horrible. Is there another way? What I need to do is setting the property:</p> <pre><code>class Foo(object): def __init__(self, v): self._v = v @ property def v(self): return self._v &gt;&gt;&gt; f = Foo(42) &gt;&gt;&gt; f.v 42 &gt;&gt;&gt; f.v = 41 AttributeError: can't set attribute ## This is what I want: a read-only attribute </code></pre> <p>but I need to do it inside a method. Is there another way? </p> <p>Thank you,<br> rubik</p> <p>P.S. I have already checked this post, but it does not solve my problem: <a href="https://stackoverflow.com/questions/3302020/using-python-property-inside-a-method">Using Python property() inside a method</a></p> <p>EDIT: I cannot use <code>property</code>, because I want to set it inside a method. I can use <code>property</code> only from outside:</p> <pre><code>class Foo(object): def __init__(self, v): self._v = v @ property def v(self): return self._v ## ...OR def getv(self): return self._v v = property(getv) </code></pre> <p>And I can't do that because I don't know the property name and I have to set it dynamically. Something like this:</p> <pre><code>class Foo(object): def __init__(self, v): self._set_property_from_inside('v', v) &gt;&gt;&gt; f = Foo(42) &gt;&gt;&gt; f.v 42 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload