定义person类,私有属性 身份证号码ID,姓名name年龄age,为私有属性添加Getters和setter方法,在Main测试类中对输入进行异常处理
时间: 2024-11-14 10:22:55 浏览: 3
Python中私有属性的定义方式
在Python中,我们可以定义一个名为`Person`的类,并将身份证号码、姓名和年龄作为私有属性。为了安全地操作这些属性,我们将创建对应的getters(获取器)和setters(设置器)。同时,我们在主类`Main`中加入异常处理机制,以便在读取或设置私有属性时确保输入的合法性。以下是具体的代码示例:
```python
class Person:
def __init__(self, _id_number, _name, _age):
self.__id_number = _id_number
self.__name = _name
self.__age = _age
# Getter and Setter methods for private attributes
@property
def id_number(self):
return self.__id_number
@id_number.setter
def id_number(self, value):
if not isinstance(value, str) or len(value) != 18:
raise ValueError("Invalid ID number format")
self.__id_number = value
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if not isinstance(value, str):
raise TypeError("Name must be a string")
self.__name = value
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
if not isinstance(value, int) or value < 0 or value > 150:
raise ValueError("Age should be an integer between 0 and 150")
self.__age = value
if __name__ == "__main__":
try:
person = Person('123456789012345678', "张三", 30)
print(person.id_number, person.name, person.age)
# Test invalid inputs
person.id_number = "123"
person.name = 123
person.age = 200
except Exception as e:
print(f"An error occurred: {str(e)}")
```
阅读全文