Home  >  Article  >  Backend Development  >  Python implements an example of allowing only one call through attributes_python

Python implements an example of allowing only one call through attributes_python

不言
不言Original
2018-04-21 14:41:251923browse

The following is an example of how Python can only be called once through attributes. It has a good reference value and I hope it will be helpful to everyone. Let's take a look together

If I want a certain method of an object to be called only once, according to my previous inertial thinking, I must define a state quantity and modify its value every time it is called. By looking at the value of the state quantity, I can decide to perform different processing.

In fact, there is another method that can not only achieve such processing, but also process the properties of the object.

First look at the following code:

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

The program execution results are as follows:

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!

From the above results, we can see that the function we described has been implemented in this way!

The above attributes are assigned default values. Of course, we can also change them to the form with assigned values:

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)

The execution result of the program is as follows:

##

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!

Related recommendations:


python limits the number of function calls

The above is the detailed content of Python implements an example of allowing only one call through attributes_python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn