如何限制某些属性从外部更改,但要保存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
例如,我想限制要从外部更改的名称属性。现在,使用此名称。如果我删除了此设置器,它将按照我的意愿工作,但是我会放宽我在设置器中进行的验证。什么是最好的方法来对我的名称属性进行验证,但不要从外部更改
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
For example I want to restrict the name attribute to be changed from the outside. Now it is possible with this name.setter. If i remove this setter it will work as I want but I will loose validations that I was made in the setter. What is the best way to keep aplying my validations for name attribute but not to be changed from the outside
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您想设置一个名称,然后使其不可变。因此,在
__ Init __
中准确地执行此操作,然后删除设置器:如果您希望以某种方式内部修改它,请使用私有方法将其设置为:
It sounds like you want to set the name once, and then make it immutable. So do exactly that in
__init__
and remove the setter:If you want it to be internally modifiable somehow, use a private method to set it: