title: How to limit values in dataclass attribute?
body: <p>I have the following dataclass <code>Gear</code> that I want to limit the maximum value for gear_level from 0 to 5.  But as you can see when I increment gear_level, it goes higher than 5, which is not what I want. I tried method as well as <strong>postinit</strong>. How do I fix this problem?</p>
  <pre><code>from dataclasses import dataclass
  
  @dataclass
  class Gear:
      gear_level: int = 0
      direction: str = None
      # more codes ...
  
      def __postinit__(self):
          if self.gear_level &lt;= 0:
              self.gear_level = 0
          elif 5 &gt; self.gear_level &gt; 0:
              self.gear_level = self.gear_level
          else:
              self.gear_level = 5
  
      def set_gear_level(self, level):
          if level &lt;= 0:
              self.gear_level = 0
          elif 5 &gt; level &gt; 0:
              self.gear_level = level
          else:
              self.gear_level = 5
  
  
  g = Gear()
  
  g.set_gear_level(6)
  
  print(g)
  
  g.gear_level += 1
  
  print(g)
  
  g.set_gear_level(-1)
  
  print(g)
  
  g.gear_level -= 1
  print(g)
  </code></pre>
  <p>Ideally, I prefer to use the g.gear_level += 1 notation, because I want to increment gear_level.  It should not jump from gear level 1 to 5.  Also, when it decrement, it should stop at 0.  It should take both an assignment of 0 and be allowed to decrement to 0. Can this be done?</p>
  <pre><code>Gear(gear_level=5, direction=None)
  Gear(gear_level=6, direction=None)
  Gear(gear_level=0, direction=None)
  Gear(gear_level=-1, direction=None)
  </code></pre>