Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k 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

2 Answers

0 votes
by (25.1k 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

Wanna become an Expert in python? Come & join our Python Certification course

0 votes
by (1.9k points)

The issue here is with the way you’ve defined the setter method. In Python, when using @property and @x.setter decorators, the setter method must be named exactly the same as the property itself, not with a different name like set_x

class C(object):

    def __init__(self):

        self._x = 0

    @property

    def x(self):

        print('getting')

        return self._x

    @x.setter

    def x(self, value):  # The setter method should also be named 'x'

        print('setting')

        self._x = value

if __name__ == '__main__':

    c = C()

    print(c.x)

    c.x = 10

    print(c.x)

This approach will allow you to access and modify x using c.x while controlling the behavior with custom print statements.

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...