本文摘自php中文网,作者不言,侵删。
下面为大家分享一篇Python通过属性手段实现只允许调用一次的示例讲解,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧如果希望一个对象的某个方法只能够调用一次,按照我之前的惯性思维,我肯定是定义一个状态量然后每次调用的时候修改它的值。通过查看状态量的数值,我可以决定采取执行不同的处理。
其实,除此之外还有一种方法,不仅仅能够实现这样的处理,还能够顺便处理对象的属性。
先看一下如下的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class DemoClass:
def __init__(self):
pass
def AttrCheck(self):
try :
self.value
print ( "already hasvalue" )
raise ValueAttrError
except AttributeError:
self.value = 0
print (self.value)
obj = DemoClass()
obj.AttrCheck()
obj.AttrCheck()
|
程序执行结果如下:
1 2 3 4 5 6 7 8 9 | grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08 $python attr1.py
0
already has value
Traceback (mostrecent call last):
File "attr1.py" , line 15, in<module>
obj.AttrCheck()
File "attr1.py" , line 8, inAttrCheck
raiseRuntimeError( "multi-excued!" )
RuntimeError:multi-excued!
|
从上面的结果看,我们所描述到的功能已经这样实现了!
上面的属性是给了默认的赋值,我们当然也可以改成带有赋值数值的形式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class DemoClass:
def __init__(self):
pass
def AttrCheck(self,value):
try :
self.value
print ( "already hasvalue" )
raiseRuntimeError( "multi-excued!" )
except AttributeError:
self.value = value
print (self.value)
obj = DemoClass()
obj.AttrCheck(123)
obj.AttrCheck(123)
|
程序的执行结果如下:
1 2 3 4 5 6 7 8 9 | grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08 $python attr1.py
123
already has value
Traceback (mostrecent call last):
File "attr1.py" , line 15, in<module>
obj.AttrCheck(123)
File "attr1.py" , line 8, in AttrCheck
raiseRuntimeError( "multi-excued!" )
RuntimeError:multi-excued!
|
相关推荐:
python 限制函数调用次数
以上就是Python通过属性手段实现只允许调用一次的示例讲解_python的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python怎么print出共轭复数
Python之post登录实例代码
Python中日期和时间格式化输出的方法小结_Python
Python file readlines() 使用方法
Python如何实现优先级队列(附代码)
Python中time库的time.time()函数的作用是什么
Python数据分析有什么用
为什么用Python写网页
Python中pow什么意思
Python列表如何去重?
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python通过属性手段实现只允许调用一次的示例讲解_python