Property method
The function of a property method is to turn a method into a static property by @property .
Class Dog (object): def __init__ (self,name): self.name = name @property def Eat (self): print ("%s Is eating "%self.name) d = Dog (" Tom ") d.eat ()
The call will be error, prompting TypeError: ' Nonetype ' objectis not callable. Because Eat has now become a static property, it is not a method. Want to call no longer need to add (), directly using D.eat can.
The normal invocation is as follows:
# _*_ Coding:utf-8 _*_class Dog (object): def __init__ (self, name): self.name = name @property def Eat ( Self): print ("%s is eating"% self.name) d = Dog ("Tom") # d.eat () d.eat
What are the eggs used to turn a method into a static property? Since you want a static variable, it is directly defined as a static variable. Well, in the future you will need a lot of scenarios that cannot simply be achieved by defining static properties, for example, if you want to know the current state of a flight, whether it arrives, is delayed, canceled, or has flown away, you have to go through the following steps to understand this state:
- Connecting Airline API Queries
- Parsing the results of a query
- Return the results to your users
So the value of this status property is a series of actions to get the result, so every time you call, it will go through a series of actions to return your results, but these action procedures do not require user care, the user only need to call this property can, understand? The pseudo code is as follows:
# _*_ Coding:utf-8 _*_class Flight (object): def __init__ (self,name): self.flight_name = name def checking_ Status (self): print ("Checking flight%s status"% self.flight_name) return 1 @property def flight_ Status (self): status = Self.checking_status () if status = = 0: print ("Flight got canceled ...") elif Status = = 1: print ("Flight is arrived ...") elif Status = = 2: print ("Flight has departured already ...")
else: print ("Cannot confirm the flight status...,please check later") F = Flight ("CA980") f.flight_status
Now I can only check the status of the flight, since this flight_status is already a property, then I can assign it? Give it a try.
f = Flight ("CA980") F.flight_statusf.flight_status = 2
Prompt Attributeerror:can ' t set attributeafter execution, unable to set properties.
Of course you can change it, but you need to pass @proerty. The setter decorator is decorated again and you need to write a new method to change the flight_status.
Note that the above code also writes a @flight_status. Deleter, which allows this property to be deleted.
python-property method of advanced object-oriented syntax