In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "Tips for using property". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "tips for using property".
Catalogue
Property attribute
Concrete examples
There are two ways to use the property property
Decorator mode
Old-style class
New class
Class attribute mode
Comparison between property object and @ property decorator
Property object class properties
@ property decorator
Property attribute
A special property that can be used like an instance property, which can correspond to a method
We should not only protect the encapsulation features of the class, but also allow developers to use objects. Property, the @ property decorator, can access the method directly through the method name without adding a pair of () parentheses after the method name.
Let's take a look at an example of finding the area of a circle.
Class Circle (object): PI = 3.14 def _ _ init__ (self R): the radius of # r circle self.r = r self.__area = self.PI * self.r * self.r @ property def area (self): return self.__area def get_area (self): return self.__areaIn [2]: C = Circle (10) In [3]: c.areaOut [3]: 314.0In [4]: c.get_area () Out [4]: 314.0
There are several points to note when defining and calling the property attribute:
When defined, the @ property decorator is added to the instance method; and there is only one self parameter
No parentheses () are required when calling
Example method: c.get_area () property decoration method: c.area concrete example
For a list page that displays a computer host in a mall, it is impossible to display all the contents of the database on the page with each request, but partially through the paging function. Therefore, when requesting data from the database, the paging function to be displayed to obtain all the data from section m to section n includes:
Calculate m and n based on the current page and total number of data requested by the user
Go to the database to request data according to m and n
Class Pager (object): def _ _ init__ (self Current_page): # the page number currently requested by the user (first page, The second page...) self.current_page = current_page # displays 10 pieces of data per page by default self.per_items = 10 @ property def start (self): val = (self.current_page-1) * self.per_items return val @ property def end (self): val = self.current_page * self.per_items Return val# ipython test In [2]: P = Pager (1) In [3]: p.start # is the starting value That is, mOut [3]: 0In [4]: p.end # is the end value, that is, nOut [4]: 10In [5]: P = Pager (2) In [6]: p.startOut [6]: 10In [7]: p.endOut [7]: there are two ways for the 20property attribute
Decorator that is: apply decorator @ property to the method
The class attribute is: define the class attribute property () whose value is property object in the class
Decorator mode
Apply the @ property decorator on the instance method of the class
The classes in Python are old-style classes and new-style classes, and the properties of new-style classes are richer than those of old-style classes.
Old-style class
Old class with an @ property decorator
Class Goods: def _ init__ (self, name): self.name = name @ property def price (self): return 100 # ipython Test In [10]: G = Goods ('watch') In [11]: g.priceOut [11]: 100New Class
New class with three @ property decorators
Class Goods: the result of executing this program with python2 and 3 is different by inheriting the object class in python3 by default. Because @ xxx.setter @ xxx.deleter "" @ property def price (self): print ('@ property') @ price.setter def price (self) is only available in python3. Value): print ('@ price.setter') @ price.deleter def price (self): print ('@ price.deleter') # ipython Test In [13]: G = Goods () In [14]: g.price@propertyIn [15]: g.price = 100@price.setterIn [16]: del g.price@price.deleter
G.price calls the price method that automatically performs @ property modification separately, and gets the return value of the method
G.price = 100 assignment automatically executes the @ price.setter modified price method and assigns 100 values to the parameters of the method
Del g.price deletes the price method that automatically performs @ price.deleter modification
Be careful
There is only one way to access properties in legacy classes, corresponding to methods modified by @ property
Properties in the new class can be accessed in three ways, and correspond to three methods modified by @ property, @ method name .setter, and @ method name. deleter
Because there are three access methods in the new class, according to the access characteristics of several attributes, we can define the three methods as the same property: get, modify, delete.
# Goods @ property application class Goods (object): def _ _ init__ (self, name, price): # original price self.original_price = price # discount self.discount = 0.8 @ property def price (self): # actual price = original price * discount new_price = self.original_price * self.discount return new_price @ price.setter def price (self Value): self.original_price = value @ price.deleter def price (self): print ('delete original price') del self.original_price # ipython test In [22]: G = Goods ('Xiaomi mobile phone') 2000) In [23]: g.priceOut [23]: 1600.0In [24]: g.price = 3000In [25]: g.priceOut [25]: 2400.0In [26]: del g.price deletes the original price of the commodity In [27]: G. -AttributeError Traceback (most recent call last) in-> 1 g.price in price (self) 12 def price (self): 13 # actual price = original price * discount-> 14 new_price = self.original_price * self.discount 15 return new_price 16AttributeError: 'Goods' object has no attribute' original_price' class attribute mode
Create a class property whose value is a property object. When you create a property property using the class attribute, there is no difference between the old class and the new class.
Class Foo: def get_bar (self): return 'get_bar' BAR = property (get_bar) # ipython Test In [32]: F = Foo () In [33]: f.BAROut [33]:' get_bar'
F.BAR automatically calls the get_bar () method and gets the return value of the method
There are four parameters in property ()
The first parameter is the method name, the calling object. Automatically triggers the execution method when the
The second parameter is the method name, the calling object. Automatically triggers the execution method when the property = XXX
The third argument is the method name, which calls the del object. Automatically triggers the execution method when the
The fourth parameter is the string, the calling object. Attribute. _ doc_, this parameter is the description of the attribute
Class Foo (object): def _ _ init__ (self, bar): self.bar = bar def get_bar (self): print ('get_bar') return self.bar def set_bar (self) Value): "" must have two parameters "" print ('set bar' + value) self.bar = value def del_bar (self): print (' del bar') del self.bar BAR = property (get_bar, set_bar, del_bar) " "bar description...") # ipython Test In [50]: F = Foo ('python') In [51]: f.BARget_barOut [51]:' python'In [52]: f.BAR = 'Java'set bar JavaIn [53]: f.BARget_barOut [53]:' Java'In [54]: comparison between del f.BARdel barproperty object and @ property decorator
Because there are three access ways to create property object attributes by class attributes, according to the access characteristics of several of their attributes, we can define three methods as the same property: get, modify, delete, and compare with the @ property decorator.
Property object class attributes # Goods class property object class properties apply class Goods (object): def _ _ init__ (self, name Price): # original price self.original_price = price # discount self.discount = 0.8 def get_price (self): # actual price = original price * discount new_price = self.original_price * self.discount return new_price def set_price (self Value): self.original_price = value def del_price (self): print ('delete original price') del self.original_price PRICE = property (get_price, set_price, del_price, "price description") # ipython Test In [59]: G = Goods ('Mac computer') 9000) In [60]: g.PRICEOut [60]: 7200.0In [61]: g.PRICE = 10000In [62]: g.PRICEOut [62]: 8000.0In [63]: del g.PRICE Delete original Price @ property Decoration # Goods @ property Decoration Application class Goods (object): def _ init__ (self, name) Price): # original price self.original_price = price # discount self.discount = 0.8 @ property def price (self): # actual price = original price * discount new_price = self.original_price * self.discount return new_price @ price.setter def price (self Value): self.original_price = value @ price.deleter def price (self): print ('delete original price') del self.original_price # ipython test In [59]: G = Goods ('Mac computer') 9000) In [60]: g.PRICEOut [60]: 7200.0In [61]: g.PRICE = 10000In [62]: g.PRICEOut [62]: 8000.0In [63]: del g.PRICE deletes the original price of the commodity
You can find that both can be implemented, but the @ property decorator has only @ property in the old class, not @ method.setter and @ method.deleter, while the new class can use both. So depending on your habits, choose one.
It takes nature tens of billions of years to create our real world, while programmers hundreds of years to create a completely different virtual world. We hit brick by brick with the keyboard and build everything with the brain. People regard 1000 as an authority, but we do the opposite and defend the status of 1024. We are not keyboard warriors, we are just extraordinary creators in the ordinary world.
At this point, I believe you have a deeper understanding of the "tips for using property". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.