[记录下学习心得] | 第040讲:类和对象:一些相关的BIF
本帖最后由 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)
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)
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)
如果是以此种方法的话, 函数名或者说是方法名可以不相同
如果是以装饰器形式使用的话, 函数名或者说是方法名必须相同, 例子代码如下:
**** Hidden Message *****
2022-06-01 推翻例子中"删除字典中内容, 这里没办法通过@modules_property.deleter以达到删除字典中某个键值"这句话:
**** Hidden Message ***** 感谢分享! 感谢分享 好 学习{:10_281:} 楼主继续加油
感谢分享 看看 感谢您的无私奉献 写挺好!
感谢分享! XIEXIE {:5_95:} 学习了 学习
学习 {:10_254:} {:10_277:} 1 感谢分享
页:
[1]
2