Python通過屬性手段實現只允許調用一次的樣本講解_python

來源:互聯網
上載者:User
下面為大家分享一篇Python通過屬性手段實現只允許調用一次的樣本講解,具有很好的參考價值,希望對大家有所協助。一起過來看看吧

如果希望一個對象的某個方法只能夠調用一次,按照我之前的慣性思維,我肯定是定義一個狀態量然後每次調用的時候修改它的值。通過查看狀態量的數值,我可以決定採取執行不同的處理。

其實,除此之外還有一種方法,不僅僅能夠實現這樣的處理,還能夠順便處理對象的屬性。

先看一下如下的代碼:

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()

程式執行結果如下:

grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python attr1.py0already has valueTraceback (mostrecent call last): File "attr1.py", line 15, in<module> obj.AttrCheck() File "attr1.py", line 8, inAttrCheck raiseRuntimeError("multi-excued!")RuntimeError:multi-excued!

從上面的結果看,我們所描述到的功能已經這樣實現了!

上面的屬性是給了預設的賦值,我們當然也可以改成帶有賦值數值的形式:

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)

程式的執行結果如下:

grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python attr1.py123already has valueTraceback (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!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.