Below for you to share a python through the property means to achieve only allow the invocation of the example of the explanation, has a good reference value, I hope to be helpful. Come and see it together.
If you want a method of an object to be called only once, according to my previous inertial thinking, I must define a state amount and then modify its value each time it is called. By looking at the number of status amounts, I can decide to take different processing.
In fact, there is another way, not only to achieve such processing, but also to handle the properties of the object.
Let's take a 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 results of the program execution are as follows:
Grey@desktop-3t80npq:/mnt/e/01_workspace/02_programme_language/03_python/03_oop/2017/08$python Attr1.py0already Have Valuetraceback (Mostrecent call last): File "attr1.py", line, in<module> obj. Attrcheck () File "attr1.py", line 8, Inattrcheck raiseruntimeerror ("multi-excued!") runtimeerror:multi-excued!
From the above results, the functions we have described have been implemented as such!
The above attribute is given the default assignment, and we can of course change to the form with the value of the assignment:
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 results of the execution of the program are as follows:
Grey@desktop-3t80npq:/mnt/e/01_workspace/02_programme_language/03_python/03_oop/2017/08$python Attr1.py123already has Valuetraceback (mostrecent): File "attr1.py", line, in<module> obj. Attrcheck (123) File "attr1.py", line 8, in Attrcheck raiseruntimeerror ("multi-excued!") runtimeerror:multi-excued!