Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python @property

作者:戮尽逆者   发布日期:2025-11-12   浏览:113

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 TypeError("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  # 这会引发 TypeError: Name must be a string.

解释说明:

  • @property 是一个装饰器,用于将类的方法转换为只读属性。它允许我们定义一个方法,但可以通过点符号访问它,就像访问属性一样。
  • @name.setter 是另一个装饰器,用于定义设置属性值的方法。它确保在设置属性时可以进行一些验证或处理。
  • 在上面的示例中,name 属性可以通过 person.name 访问和修改,但不能直接赋值为非字符串类型,否则会引发 TypeError

上一篇:python中lambda用法

下一篇:python 数字转字符串

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站