0 votes
1 view
in Python by (12.5k points)

I'm trying to execute the following python code:

class C(object):

    def __init__(self):

        self._x = 0

    @property

    def x(self):

        print 'getting'

        return self._x

    @x.setter

    def set_x(self, value):

        print 'setting'

        self._x = value

if __name__ == '__main__':

    c = C()

    print c.x

    c.x = 10

    print c.x

But I get the following error:

pydev debugger: starting

getting

0

File "\test.py", line 55, in <module>

c.x = 10

AttributeError: can't set attribute

1 Answer

0 votes
by (24.8k points)
edited by

The reason you are getting this error is because you are naming the setter method incorrectly. You have named the setter method as set_x which is incorrect, this is why you are getting the Attribute Error.

To fix this error, instead of naming it as set_x you need to give it the same name as the property you creating a setter for, in you case you can do it like this:

@x.setter

def x(self, value):

    'setting'

    self._x = value

If you wish to learn more about OOP in python, watch this video

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...