Python: AttributeError: can not set attribute. I can not create my instance

0

I have an error creating my instance

#! python3

class Profile(object):
    """contiene la informacion del perfil"""
    def __init__(self):
        self.name = None    

    @property
    def name(self):
        """name"""
        return self.name

if __name__ == '__main__':
    profile1 = Profile()

The error that throws me:

Traceback (most recent call last):
File "F:\Project\profile.py", line 14, in <module>
  profile1 = Profile()
File "F:\Project\profile.py", line 6, in __init__
  self.name = None  
AttributeError: can't set attribute

I was turning it around for a while, but I can not make sense of it

    
asked by isbrqu 31.12.2017 в 23:37
source

1 answer

0

The problem is caused because your attribute self.name is colliding with the property name, and in doing so you want to use the setter of the property. The common thing is to set the name of the attribute with: _ , for example in your case change self.name with self._name .

class Profile(object):
    """contiene la informacion del perfil"""
    def __init__(self):
        self._name = None    

    @property
    def name(self):
        return self._name

if __name__ == '__main__':
    profile1 = Profile()

Or implement the setter:

class Profile(object):
    """contiene la informacion del perfil"""
    def __init__(self):
        self.name = None    

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

if __name__ == '__main__':
    profile1 = Profile()
    
answered by 31.12.2017 / 23:44
source