class Test:
  def __init__(self,number)
  	self.number = number

if __name__ == '__main__':
  test = Test(1)
  print(test.number)
  test.number = -100
  print(test.number) 
@property
  • 调用被装饰方法的时候不+括号
  • 方法定义有且只能有self一个参数
class Test:
    def __init__(self, number):
        self.__number = number

    @property  # 声明number属性,只读
    def number(self):
        if self.__number >= 100:
            raise ValueError('范围超出100')
        return self.__number


if __name__ == '__main__':
    test = Test(3)  
    print(test.number)  # 3

@func.setter
class Test:
  def __init__(self,number):
    self.__number = None
    
  @property # 声明属性
  def number(self):
    if self.__number >= 100:
      raise ValueError('范围超出100')
    return self.__number
  
  @number.setter # 设置属性
  def number(self,number)
  		self.__number = number
    
'''
声明和设置属性的函数名字可以完全自定义,但是要与初始化变量名做区分,如果都一样的话会出现同名递归报错
'''

test = Test()
test.number = 30  # setter 设置值
print(test.number) #property声明的number获取值
@func.deleter
class Test:

    def __init__(self):
        self.__number = None

    @property
    def number(self):
        return self.__number

    @number.setter
    def number(self, number):
        self.__number = number

    @number.deleter
    def number(self):
        self.__number = 100


if __name__ == '__main__':
    test = Test()
    test.number = 10
    print(test.number)  # 10
    del test.number
    print(test.number)  # 100
'''
该示例中,deleter的方法中将number设置为了100,
del test.number后触发该流程,所以在deleter做什么事情,由自己决定,
可以是 del self.__number 也可有是self.__number=None等等,del只是触发条件
'''
property(fget,fset)
class Test:

    def __init__(self):
        self.__number = None

    def get_number(self):
        return self.__number

    def set_number(self, number):
        self.__number = number

    def del_number(self):
        del self.__number

    # 设置number属性指向property对象
    # fget 获取的时候触发的方法
    # fset 赋值的时候触发的方法
    # fdel 删除的时候触发的方法

    number = property(fget=get_number, fset=set_number, fdel=del_number)


if __name__ == '__main__':
    test = Test()
    test.number = 100
    print(test.number)
    del test.number

04-13 03:31