Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python can't use setter

here is my issue, when i’m using @property decorator I can’t use setter

class Worker:

def __init__(self,name):
    self.__name = name

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

@name.setter
def set_name(self,new_name):
    self.__name = new_name

worker1 = Worker('A')
print(worker1.name)
worker1.name = 'B'
print(worker1.name)

It gives AttributeError: can’t set attribute ‘name’, when I use setter

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Let’s rewrite this without decorator syntax.

class Worker:

    def __init__(self,name):
        self.__name = name
    
    def name(self):
        return self.__name
    name = proprety(name)
    
    def set_name(self,new_name):
        self.__name = new_name

    set_name = name.setter(set_name)

This makes it easier to see that you now have two similar properties: name, which only provides read-only access to the __name attribute, and set_name, which has a getter and a setter for the same attribute. name.setter takes a method, and returns a new property that replaces the old setter (if any) if name with the given function.

You want a single property named name, so you must use the same name when defining the setter.

class Worker:

    def __init__(self,name):
        self.__name = name
    
    @property
    def name(self):
        return self.__name
    name = proprety(name)
    
    @name.setter
    def name(self,new_name):
        self.__name = new_name

The decorators are a way to simplify code like the following:

class Worker:

    def __init__(self,name):
        self.__name = name
    
    def get_name(self):
        return self.__name
    
    def set_name(self,new_name):
        self.__name = new_name

    name = property(get_name, set_name)
    del get_name, set_name
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading