How should I expose read-only fields from Python classes?

前端 未结 5 1903
野趣味
野趣味 2020-12-28 13:51

I have many different small classes which have a few fields each, e.g. this:

class Article:
    def __init__(self, name, available):
        self.name = name         


        
5条回答
  •  独厮守ぢ
    2020-12-28 14:18

    I would use property as a decorator to manage your getter for name (see the example for the class Parrot in the documentation). Use, for example, something like:

    class Article(object):
        def __init__(self, name, available):
            self._name = name
            self.available = available
    
        @property
        def name(self):
            return self._name
    

    If you do not define the setter for the name property (using the decorator x.setter around a function) this throws an AttributeError when you try and reset name.

    Note: You have to use Python's new-style classes (i.e. in Python 2.6 you have to inherit from object) for properties to work correctly. This is not the case according to @SvenMarnach.

提交回复
热议问题