Home > Mobile >  Python can't use setter
Python can't use setter

Time:10-06

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

CodePudding user response:

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

CodePudding user response:

Change set_name to name.

Python docs for @property:

Be sure to give the additional functions the same name as the original property (x in this case.)

  • Related