Search code examples
pythonpropertiessetter

Conventions for property method, <>.setter and setter method names


Is there a convention for naming:

1.- the property method: in the example below, " def get_number (...)". Is that a good name? Should it be another one?

2.- the setter: in the example below "get_number.setter". Does it has always to be <PropertyMethod>.setter ?

3.- the setter method: in the example below: "def number (...)". Is it ok to use the variable name as the method?

class Contact:
    def __init__(self, in_number):
        self._number = in_number
    
    @property
    def get_number(self): 
        return self._number

    @get_number.setter  
    def number(self, value): 
        self._number = value

I haven't find it in the documentation.


Solution

  • Answering my question:

    class Contact:
        def __init__(self, in_number):
            self._number = in_number
    
        @property
        def my_number(self): #1
            return self._number
    
        @my_number.setter  #2
        def my_number(self, value): #3
            self._number = value
    
    esther = Contact(6)
    print(esther.my_number)
    esther.my_number = 8
    print(esther.my_number)
    
    • #1 This method name can be watever you want to be, as long as it has sense for retrieving the value of the private variable.

    • #2 the @setter has to have the same name as the property method

    • #3 The setter method can be named as wished, but for it to make sense for the user, use the same name as the @property method