python笔记12 类的成员,property装饰器

    科技2025-07-16  11

    python笔记12 类的成员,property装饰器

    先声明一下 各位大佬,这是我的笔记。 如有错误,恳请指正。 另外,感谢您的观看,谢谢啦!

    嗯,processon真好用

    下面来用实例举例

    class test(): str0 = '我是静态字段,是大家共享的' def __init__(self): self.str01 = '我是普通字段为对象特有,也只有对象能更改我' def test01(self): print(self.str01) @staticmethod def test02(): str03 = '我是静态方法,对象和类都可以调用我' print(str03) @classmethod def test03(cls): print('我是类方法,对象和类都可以调用我') li1 = test() print(test.str0) print(li1.str0) print(li1.str01) li1.test01() li1.test02() li1.test03() 我是静态字段,是大家共享的 我是静态字段,是大家共享的 我是普通字段为对象特有,也只有对象能更改我 我是普通字段为对象特有,也只有对象能更改我 我是静态方法,对象和类都可以调用我 我是类方法,对象和类都可以调用我

    property装饰器

    这个装饰器可做到以调用变量的形式,调用函数,非常的方便,

    它有两种编写方法接下来一一介绍

    class test(): def __init__(self): self.num = 1 @property def test02(self): print(f'--{self.num}--') l1 = test() l1.test02 --1--

    这是让你可以用访问变量的形式访问这个方法

    那么既然是变量就应该有修改值,和删除的的操作

    class test(): def __init__(self): self.num = 1 @property def test02(self): print(f'--{self.num}--') @test02.setter def test02(self,num): print(f'--{num}--') @test02.deleter def test02(self): print(f'--{num}--') del self.num print(f'--{num}--') l1.test02 = 2

    这条语句就可以进入有setter装饰器的函数中

    --2-- del l1.test02

    这条语句就会进入有着deleter装饰器的函数中

    --2-- NameError: name 'num' is not defined

    结果报错了却恰恰说明删除成功了

    不过property还有另一种编写方法

    class test(): def __init__(self): self.__num = 1 def get_num(self): print(f'--{self.__num}--') return self.__num def set_num(self,num): print(f'--{num}--') def del_num(self): print(f'--{__num}--') del self.num print(f'--{__num}--') num = property(fget=get_num,fset=set_num,fdel=del_num) l1 = test() l1.num l1.num =9 --1-- --9-- del l1.num --9-- NameError: name 'num' is not defined

    1 = test()

    l1.num l1.num =9

    –1-- –9--

    del l1.num

    –9-- NameError: name ‘num’ is not defined

    Processed: 0.009, SQL: 8