vendredi 2 août 2019

Is it a good practice to define unchanged public variables in Python?

Suppose that we had a class that at a certain point after creation will need to get assigned a value:

class ProcStatus:
    def __init__(self, name):
        self.name = name
        self._status_code = None

    def set_status_code(self, value):
        self._status_code = value

    def print_proc_status(self):  # Some function that does something with the status code
        print(f'{self.name} returned code {self._status_code}')


status = ProcStatus('ls')
# Some code in between
status.set_status_code(1)
status.print_proc_status()

Using this design, it's clear by the interface that the caller can (and is encouraged to) explicitly set the status code. However, the more pythonic approach would be using an attribute:

class ProcStatus:
    def __init__(self, name):
        self.name = name
        self.status_code = None

    def print_proc_status(self):  # Some function that does something with the status code
        print(f'{self.name} returned code {self.status_code}')


status = ProcStatus('ls')
# Some code in between
status.status_code = 1
status.print_proc_status()

Is the second one a better design, despite looking a little misleading since status_code is never updated within the class? Alternatively, would a property setter and getter assigning to a private field be the right approach?

Aucun commentaire:

Enregistrer un commentaire