Getter and setter methods in a Peewee model
<p>I have the following simple model in Peewee:</p>

<pre><code>class SiteText(BaseModel):
    url = TextField()
    text = TextField()
    my_counter = IntegerField()

    def get_text_by_url(url):
        d = [s.text for s in SiteText.select(SiteText.url == url)]
        d = d[0] if len(d) &gt; 0 else None
        return d

    def save_text(updates):
        # updates is a dict containing, url, text, my_counter
        SiteText.upsert(**updates)

    def get_outage_counter(url):
        c = [c.my_counter for c in SiteText.select(SiteText.url == url)]
        c = c[0] if len(c) &gt; 0 else None
        return c

    def set_outage_counter(url, counter):
        c = SiteText.get(SiteText.url == url)
        c.counter = counter
        c.save()
</code></pre>

<p>However, it feels rather strange writing getters and setters for some of the attributes. Is there a more Pythonic way of doing this? Should I, for example, have a single method for getting and setting the outage counter for a specified URL? Should I convert the getter and setter functions to properties (though then they would clash with the actual attributes). Feedback welcome!</p>

<p>Actualy using proporties wouldn't clash with your actual attribute name, because they can be different than the getter/setter function.</p>

<pre><code>class Example:
    def __init__(self):
       self.value = 5

    @property
    def value(self):
        print('Entering value getter')
        return self._value

    @value.setter
    def value(self, val):
        print('Entering value setter')
        self._value = val
</code></pre>

<p>Let say we have the class as above. You can see that the getter function is returning <code>_value</code> which might be strange for someone who would see that in <code>__init__</code> method there is only <code>self.value = 5</code> but not <code>self._value</code>.</p>

<p>Let say that we do this next:</p>

<pre><code>a = Example()
</code></pre>

<p>Just after instantiating the class object, <code>__init__</code> is calling the <code>value.setter</code> function due to <code>self.value = 5</code>, and because of that, we got:</p>

<pre><code>a = Example()
Entering value setter
print(a.value)
Entering value getter
5
print(a.__dict__)
{'_value': 5} # _value was created in setter function
</code></pre>

<p>So as you can see, u can use property that way and be fine with it.</p>

python peewee