class Person:
    def __init__(self, name):
        self._name = name
    @property
    def name(self):
        """Getter method for the name attribute."""
        return self._name
    @name.setter
    def name(self, value):
        """Setter method for the name attribute."""
        if not isinstance(value, str):
            raise ValueError("Name must be a string.")
        self._name = value
# 示例用法
person = Person("Alice")
print(person.name)  # 输出: Alice
person.name = "Bob"
print(person.name)  # 输出: Bob
# person.name = 123  # 这会引发 ValueError: Name must be a string.@property 装饰器将方法转换为属性,允许我们像访问普通属性一样访问该方法。@name.setter 装饰器定义了设置属性值时的行为。这里我们添加了一个简单的验证,确保 name 属性只能被设置为字符串。name 设置为非字符串类型,将会抛出 ValueError 异常。上一篇:python中int
下一篇:python中split
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站