Python--property (Make a method look like a class property)

Source: Internet
Author: User

Tag:format    No    app    change     code      exception    hello   elf   int   

"" "Adorner property:     makes a method look like a class property" "" #例子1class  a:    def __ Init__ (self,  x, y):         self.__x = x   #私有变量         self.__y = y    def  __add (self):  #私有方法         return self.__x +  self.__y     @property     def sum (self):  # When modified with the property adorner, the method looks like an attribute         return self.__add () if __ name__ ==  ' __main__ ':     a = a (5,6)     print (a.sum   #外部调用sum, it looks like a property, this property is actually a method that does not function in the calculation # example 2class foo:     @property      def foo (self):        return  "bar" f =  Foo () print (F.foo) Example 3class foo:     @property     def foo (self):         return self._foo     @foo .setter  #使用foo方法的setter属性又装饰了这个foo方法, This foo and the above Foo are just the same name, actually different     def foo (Self, value):         self._foo = valuef = foo () f.foo = 100print (F.foo) #一定要注意了, The function that is decorated by the property decorator returns an Object # example 4class silly:     @property     def  silly (self):         print ("you are getting silly" )         return self._silly  #返回的是一个property对象       @silly. setter    def silly (Self, value):         print ("you are making silly {}". Format (value))          self._silly = value     @silly .deleter  #删除函数 (currently I don't know how to use it)      def silly (self):         print ("whoah you killed  silly! ")         del self._sillys = Sillys.silly =  100print (s.silly) #再看最后的一个例子, a price attribute in an Apple class class apple:    def __init__ (self,  Price):         self.price = pricea = apple (19) Print (A.price) a.price = 20  #随意被更改了, there is a data security issue print (A.price) #改进代码v1 .0class apple:     def __init__ (self, price):         self._price  = price  #将属性增加单下划线, turn semi-protected a = apple   #初始化价格print (a._price)   # Print a.price = 25  #尝试的修改print (a._price)   #貌似没有修改成功, or the original 19# continue to improve  v1.0.1class apple:     d ef __init__ (Self, price):        self._price =  Pricea = apple ("Hello")   #price是价格, but being passed in is a string, which means that data that is randomly passed into different data types needs to continue to improve print (A._price) #继续改进  v1.0.2class apple (object):     def get_price (self):         return self.__price    def set_score (Self, price):         if not isinstance (Price, int):             raise valueerror (' Price must be  an integer! ')         self.__price = pricea = apple () A.set_score   #那么可以再试试传入字符串, the exception is thrown by print (A.get_price ()) #最终版本  v2.0class apple (object):      @property     def get_price (self):        & nbsp;try:            return self.__price         except AttributeError:             print ("No data ...")      @get_price. setter #@ The property itself creates another adorner @get_price.setter, which is responsible for turning a setter method into an attribute assignment     def set_score (self,  price):         if not isinstance (Price, int):             raise valueerror (' Price must  be an integer! ')         self.__price = pricea = apple () A.set_score  = 20print (A.get_price)


Python--property (Make a method look like a class property)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.