如何限制某些属性从外部更改但将验证保存在 Python

How to restrict certain attribute to be changed from the outside but to save the validation in Python

class Town:
     
    def __init__(self, name: str, country: str, population: int):

        #assert len(name) > 1, "The name of the town must be at least two characters long"
        self.name = name
        self.county = country
        self.population = population

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

    @name.setter
    def name(self,value):
        if len(value) < 2 or len(value) > 50:
            raise ValueError("The Name of the town must be between 2 and 50 characters")
        self.__name = value

例如我想限制从外部更改名称属性。现在可以用这个name.setter。如果我删除这个 setter,它会按我想要的方式工作,但我将失去对我在 setter 中所做的验证。什么是继续应用我的名称属性验证但不从外部更改的最佳方法

听起来你想设置一次名称,然后使其不可变。所以在 __init__ 中完全这样做并删除 setter:

class Town:
    def __init__(self, name: str, country: str, population: int):
        if len(name) < 2 or len(name) > 50:
            raise ValueError("The Name of the town must be between 2 and 50 characters")

        self.__name = name
        self.county = country
        self.population = population

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

如果您希望它可以在内部以某种方式进行修改,请使用私有方法来设置它:

class Town:
    def __init__(self, name: str, country: str, population: int):
        self.__set_name(name)
        self.county = country
        self.population = population

    def __set_name(self, value):
        if len(value) < 2 or len(value) > 50:
            raise ValueError("The Name of the town must be between 2 and 50 characters")
        self.__name = value

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