|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 TC_DHL 于 2022-6-1 00:23 编辑
修饰符: classmethod | staticmethod | property
如果有不对的地方,欢迎指正, 互相学习哈!
修饰符:类方法 @classmethod | 无需显式地传递类名做实参
- class Computer:
- # 类属性modules
- __modules = {"cpu":"Intel", "内存":"镁光", "硬盘":"970-Pro"}
- # 设定修饰符@类方法 | 类的函数或者叫类的方法output_modules
- @classmethod
- def output_modules(cls):
- for (i,s) in cls.__modules.items():
- print(i, ':', s)
- # 调用类的方法output_modules,无需显式地传递类名做实参
- Computer.output_modules()
- #-------------------------------------------------------------
- # 输出结果:
- # cpu : Intel
- # 内存 : 镁光
- # 硬盘 : 970-Pro
复制代码
也可被其他类直接进行调用(感觉有点全局的意思), 看例子代码如下:
- class Computer:
- # 类属性modules
- __modules = {"cpu":"Intel", "内存":"镁光", "硬盘":"970-Pro"}
- # 设定修饰符@类方法 | 类的函数或者叫类的方法output_modules
- @classmethod
- def output_modules(cls):
- for (i,s) in cls.__modules.items():
- print(i, ':', s)
- class OtherClass:
- def __init__(self):
- pass
- def _test_OtherClass(self):
- # 调用类的方法output_modules,无需显式地传递类名做实参
- Computer.output_modules()
- aaaa = OtherClass()
- aaaa._test_OtherClass()
- #-------------------------------------------------------------
- # 输出结果:
- # cpu : Intel
- # 内存 : 镁光
- # 硬盘 : 970-Pro
复制代码
修饰符:静态方法 @staticmethod | 必须显式地传递类名做实参
- class Computer:
- # 类属性modules
- __modules = {"cpu":"Intel", "内存":"镁光", "硬盘":"970-Pro"}
- # 在静态方法search_module中定义形参var,准备传递类:Computer
- # 调用时必须显性地传递类名,才能实现类方法一样的效果
- # 设定修饰符@静态方法 | 类的函数或者叫类的方法search_module
- @staticmethod
- def search_module(var, module_value):
- print(var.__modules[module_value])
- Computer.search_module(Computer, "cpu")
- Computer.search_module(Computer, "内存")
- Computer.search_module(Computer, "硬盘")
- #-------------------------------------------------------------
- # 输出结果:
- # Intel
- # 镁光
- # 970-Pro
复制代码
也可被其他类直接进行调用(有点全局的意思.....), 看例子代码如下:
- class Computer:
- # 类属性modules
- __modules = {"cpu":"Intel", "内存":"镁光", "硬盘":"970-Pro"}
- # 在静态方法search_module中定义形参var,准备传递类:Computer
- # 调用时必须显性地传递类名,才能实现类方法一样的效果
- # 设定修饰符@静态方法 | 类的函数或者叫类的方法search_module
- @staticmethod
- def search_module(var, module_value):
- print(var.__modules[module_value])
- class OtherClass:
- def __init__(self):
- pass
- def _test_OtherClass(self):
- # 调用类的静态方法search_module,必须显式地传递类名做实参
- Computer.search_module(Computer, "cpu")
- Computer.search_module(Computer, "内存")
- Computer.search_module(Computer, "硬盘")
- aaaa = OtherClass()
- aaaa._test_OtherClass()
- #-------------------------------------------------------------
- # 输出结果:
- # Intel
- # 镁光
- # 970-Pro
复制代码
@property 此修饰符可赋值给变量, 语法为:x = property(getx, setx, delx)
如果是以此种方法的话, 函数名或者说是方法名可以不相同
如果是以装饰器形式使用的话, 函数名或者说是方法名必须相同, 例子代码如下:
2022-06-01 推翻例子中"删除字典中内容, 这里没办法通过@modules_property.deleter以达到删除字典中某个键值"这句话:
|
|