Search code examples
pythonclasscoding-style

Python class objectivity convention


Is it a good style to create classes like that ? I read the PEP8 document but I didn't saw any good example. If not how is it a proper way ? Thanks for any answers.

class Zone:
    def __init__(self, index=None, name=None):
        self._index = index
        self._name = name

    @property
    def index(self):
        return self._index

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

    @index.setter
    def index(self, index):
        self._index = index

    @name.setter
    def name(self, name):
        self._name = name

Solution

  • Your setters and getters don't do anything. With your implementation, the user of this class does this:

    z = Zone()
    z.name = 'foo'
    print(z.name)
    

    Compare to this implementation:

    class Zone:
        def __init__(self, index=None, name=None):
            self.index = index
            self.name = name
    
    
    z = Zone()
    z.name = 'foo'
    print(z.name)
    

    It works exactly the same with a lot less code.

    Unless you do anything in your setters and/or getters, you don't need them.