0

I have to use the setter part of Python and I thought I understood but I guess I don't. I have tried to change the parameters of the object, I have been wrestling with the declarations in the initialization and stuff, but I just don't seem to be getting it. Python gives me the error

Traceback (most recent call last):
  File "C:\Users\mkrui\workspace\YiviY\yiviy.py", line 71, in <module>
frits.position['x'] += random.randint(-15,15) #make object
  File "C:\Users\mkrui\workspace\YiviY\yiviy.py", line 45, in position
return self._position
AttributeError: 'lifeform' object has no attribute '_position'

Code:

class lifeform(object):
    kind = "lifeform"
    def __init__(self, max_age = (100), speed = (50), sati = (80), max_sati = (100), position = {'x': random.randint(0,WIDE), 'y': random.randint(0,HIGH)}):
        self.age = 0
        self.max_age = max_age
        self.speed = speed
        self.strength = 100 - speed
        self.sati = sati
        self.max_hunger = max_sati
        self.size = 10
        self.color = [155,155,255]
        self.position = position

    @property
    def position(self):
        return self._position

    @position.setter
    def position(self, pos):
        if pos['x'] > WIDE:
            self._position['x'] = WIDE - 20
        elif pos['x'] <0:
            self._position['x'] = 20
        if pos['y'] > HIGH:
            self._position['y'] = HIGH - 20
        elif pos['y'] <0:
            self._position['y'] = 20
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
mtjiran
  • 292
  • 1
  • 2
  • 12
  • There are numerous cases where you *don't* assign to `_position` in the setter... – jonrsharpe Oct 16 '17 at 21:00
  • Please help me, what am I missing. The assigment should be to self._position right? Or is it the problem I am trying to update a library part? – mtjiran Oct 16 '17 at 21:04
  • 1
    Think about what happens when `0 <= pos['x'] <= WIDE`, for example... Also note that you will not get a random value for each instance, if that's what you were expecting. – jonrsharpe Oct 16 '17 at 21:07
  • 1
    I was not expecting to get a random number every time, It should be initialized random. Changed my code and now the error is gone, I have just created a new problem for myself, it does not catch the if statement. But thank you very much! Your last remark helped a lot! – mtjiran Oct 16 '17 at 21:24
  • 1
    OK, but also note that a mutable default is a [very bad idea](https://stackoverflow.com/q/1132941/3001761). Glad you sorted it! – jonrsharpe Oct 16 '17 at 21:26
  • Is a default value of an object determined per instance, or per definition? Because when it is per definition, I shoudl assign a value at the initialisation. – mtjiran Oct 16 '17 at 21:36
  • Please read what I linked, it explains exactly when and how the default values are set. Given that you no longer have this question, I suggest you delete it. – jonrsharpe Oct 16 '17 at 21:36

0 Answers0