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

前端 未结 5 1881
野趣味
野趣味 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:29

    As pointed out in other answers, using a property is the way to go for read-only attributes. The solution in Chris' answer is the cleanest one: It uses the property() built-in in a straight-forward, simple way. Everyone familiar with Python will recognize this pattern, and there's no domain-specific voodoo happening.

    If you don't like that every property needs three lines to define, here's another straight-forward way:

    from operator import attrgetter
    
    class Article(object):
        def __init__(self, name, available):
            self._name = name
            self.available = available
        name = property(attrgetter("_name"))
    

    Generally, I don't like defining domain-specific functions to do something that can be done easily enough with standard tools. Reading code is so much easier if you don't have to get used to all the project-specific stuff first.

提交回复
热议问题