Python property属性

一、概念

  • property属性是一种特殊的装饰器,用于将方法转换为属性。

二、作用

  • 它通常与@property装饰器一起使用,以便在获取和设置属性值时执行一些额外的操作。

三、实战

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

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

    @name.setter
    def name(self, value):
        if not isinstance(value, str):
            raise ValueError("姓名必须是字符串类型")
        self._name = value

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if not isinstance(value, int):
            raise ValueError("年龄必须是整数类型")
        if value < 0:
            raise ValueError("年龄不能为负数")
        self._age = value

p = Person("张三", 25)
print(p.name)  # 输出:张三
print(p.age)   # 输出:25

p.name = "李四"
p.age = 30
print(p.name)  # 输出:李四
print(p.age)   # 输出:30

四、小结

  • setter属性通常需要和property一起使用,否则会提示错误。
  • property属性列表
    def deleter(self, *args, **kwargs): # real signature unknown
        """ Descriptor to change the deleter on a property. """
        pass

    def getter(self, *args, **kwargs): # real signature unknown
        """ Descriptor to change the getter on a property. """
        pass

    def setter(self, *args, **kwargs): # real signature unknown
        """ Descriptor to change the setter on a property. """
        pass

你可能感兴趣的:(python)