Python full Stack development "the 15th" object-oriented three major features--encapsulation

Source: Internet
Author: User
Tags custom name

1. Package:

What is encapsulation? (Encapsulation is not a pure meaning of the hidden, in fact, it can still be viewed)

is to hide something that you don't want others to see.

Encapsulating data: Purpose is to protect privacy

Functional encapsulation: Designed to isolate complexity

If you use private, the deformed property cannot be used directly outside of the class, but can be used directly inside the class

# object name. Three ways to take the value of a property name 1. Use self in our usual __init__ method class Course: #恰好给我们提供了实现这种思路的方法 #             #一种思路, Python    def __init__ (self , price,period,name):        self.price = Price        Self.period = period        Self.name = Namec = Course (+, ' Linux ', ' 6 Months ') print (C.period) 2. Define an empty dictionary inside the class, and then load the dictionary with the value def course (price,name, period):    dic = {}    dic[' price '] = Price    dic [' name '] = name    dic [' period '] = period    return DICC = Course (+, ' python ', ' 6 months ') print (c.period) c10/> #对象名. Property name     View the value of the property 3. Take advantage of the Namedtuple method from collections import namedtuple  #只有属性没有方法的类Course = Namedtuple (' Course ', [' name ', ' price ', ' period ']) #传两个参数, the first is a custom name, and the second goes in the property Python = Course (' python ', 10000, ' 6 moths ')  # Equivalent to instantiation of print (Python.name)

2. Encapsulating a private property of a class property (that is, the Class property is preceded by __)

#类属性1class Goods:    # In accordance with the 80 percent calculation (defined a private class property)    __discount = 0.8  #变形后: _goods__discount    def __init__ (self, Name,price):        self.name = name        Self.price = Price    def goods_price (self):        return  self.price * goods . __discountapple = Goods (' Apple ') print (Apple.goods_price ()) # Print (goods.__dict__)  #类名. __dict__print (Goods . _goods__discount)

#类属性的私有方法 # Package: Hide what you don't want to see # Data encapsulation: Purpose to protect privacy class Teacher:    __school = ' Oldboy '  #类属性    def __init__ (self,name , salary):        self.name = name self        . __salary  =  salary  #_Teacher__salary            # Teacher's property   value        #怎么把薪水隐藏起来?        self.__salary=salary    def foo (self):        print ('------') t=teacher (' Egon ', +) print (t.__dict__) # Print (t.name) print (t._teacher__salary) #让显示出来print (teacher._teacher__school)  #类属性使用_类名__属性名t. Foo () # In this class can be called normal # in this class must be called with the _ Class name __ property name (but not recommended)

  

3. Encapsulating private properties of class objects

Adult BMI: Too light: Less than 18.5 normal: 18.5-23.9 overweight: 24-27 obese: 28-32 very obese, higher than 32 body mass index (BMI) = weight (kg) ÷ height ^2 (m) ex:70kg÷ (1.75x1.75) =22.86
# calculates the BMI, the standard for measuring human health (private property of an object) class Person:def __init__ (Self,height,weight, Name,sex): self.__height = height #私有属性 (let you no longer tune it out) # in this class can be called, outside the class can not call the self . __weigth = Weight Self.__name = name Self.__sex = Sex def tell_bmi (self): #体重指数 return Self.__we   Igth/self.__height * * 2 #在本类中可以调用 def tell_height (self): print (self.__height) def tell_weight (self):             #告诉体重 return self.__weigth def set_weigth (self,new_weight): #修改体重 if New_weight >20: Self.__weigth = new_weight else:raise TypeError (' You are too thin, thin even the number of pounds (fast) No ') #如果体重小于20或者负的, on the initiative to prompt an error egg = Per Son (1.6,96, ' Haiyan ', ' female ') print (Egg.tell_bmi ()) # egg.__height #在类外不能调用 # print (egg._person__height) # View outside the class call print (egg.__dict__) #查看变形后的类型 # egg.set_weigth ( -10) # Print (Egg.tell_weigth ()) Egg.set_weigth (66) # Modified weight of 66print (Egg.tell_weight ()) 
# Private properties of object properties Two class people:    def __init__ (self,name,age,sex,height):        self.__name = name        Self.__age = Age        self.__sex = sex        self.__height = height    def tell_name (self):  #看人名字        Print (self.name)    def set _name (self,val): #修改名字        if not isinstance (Val, str):            raise TypeError (' name must be String type ')        Self.__name = val    def tell_info (self):         print ("           ---------%s info-----------           name:%s           age:%s           sex:%s           height:%s "% (self.__name,self.__name,self.__age,self.__sex,self.__height)) P=people (' Egon ', +, ' male ', ' ') P.tell_info () p.set_name (' Haiyan ')   #调用修改名字的方法p. Tell_info () # Print (p._people __name) #就可以看到了

  

4. Encapsulating private properties of a class method

Private property of the class method the private property of the # method class Parent:    def __init__ (self):        self.__func ()  #__func ==_parent__func    def __ Func (self):        print (' parent func ') class Son (parent):    def __init__ (self):        self.__func ()  #_Son__func    def __func (self):        print (' son func ')    def _parent__func (self):        print (' son _parent__func ') s = Son () Print (parent.__dict__)  #类名. __dict__ look at the results of the transformation # Private properties: In this class is a normal call #           in this class must be called with the _ Class name __ property name (but not recommended)
#方法的私有属性2class Foo:    def __func (self):        print ("From Foo") class Bar (Foo):    def __func (self):        print ( ' From bar ') B = Bar () B._foo__func () B._bar__func ()
#装饰方法的私有属性3class Foo:    def __init__ (self,height,weight):        self.height = height        self.weight = weight    def __heightpow (self):  #私有方法        return self.height * self.height    def tell_bmi (self):        return Self.weight /self.__heightpow () Egon = Foo (1.7,120) print (EGON.TELL_BMI ()) print (foo.__dict__) print (Egon._foo__heightpow ())  #虽说是私有的, but you can still see it.

5.property

Why use the property: After the function of a class is defined as an attribute, when the object is used again obj.name, it is impossible to realize that its name is executed a function and then calculated, the use of this feature follows the principle of unified access

1. Calculate the area and perimeter of a circle

From math import Piclass Circle:    def __init__ (Self,radius):        Self.radius = Radius    @property  # Adorner: A method is used as a property with    def area (self):        return Self.radius * self.radius* pi    @property    def peimeter (self):        return 2*PI*SELF.RADIUSC = Circle print (c.area)  #当成一个属性来调了, no brackets are used for print (c.peimeter)

2. Caching Web page information

From urllib.request import Urlopenclass web_page:    def __init__ (self,url):        self.url = URL        self.__ Content = None  #内容设置为None    @property    def content (self):        if self.__content:  #如果不为空, that means it has been downloaded  _web_page__content            return self.__content        else:            self.__content = Urlopen (Self.url). Read () #做缓存            return self.__contentmypage = Web_page (' http://www.baidu.com ') print (mypage.content) print (mypage.content) Print (mypage.content)

3. Sum, average, maximum, minimum

Class Num:    def __init__ (Self,*args):        print (args)        if Len (args) ==1 and (type (args[0]) is List or type (Args[0] ) is a tuple):            Self.numbers=args[0]        else:            self.numbers = args    @property    def sum (self):        return SUM (self.numbers)    @property    def avg (self):        return Self.sum/len (self.numbers)    @property    def min (self):        return min (self.numbers)    @property    def max (self):        return max (self.numbers) num = Num ([3,1,3]) VVV = num (8,2,3) print (num.sum) print (num.min) print (num.avg) print (Num.max) print ('-----------') print ( vvv.sum) print (vvv.min) print (vvv.avg) print (Vvv.max)

6.setter

#买东西class Goods:    __discount = 0.8  #类的私有属性    def __init__ (self,name,price):        self.name = name        self._ _price = Price    @property    def Price (self):        # if Hasattr (self, ' __price '):            return Self.__price * goods.__ Discount        # Else:        #     raise Nameerror    @price. Setter    def Price (Self,new_price):        If Type ( New_price) is int:            self.__price = New_price    @price. Deleter    def Price (self):        del self.__ Priceapple = Goods (' Apple ', #) # print (apple.price) Apple.price = 20print (apple.price) # del apple.price# print ( Apple.price) # Apple.set_price ($) # Apple._goods__apple
@property to disguise a method in a class as a property
Turns out to be Obj.func ()
Now is Obj.func--- properties
1. Because properties cannot be modified
So I used @funcname.setter.
Obj.func = New_value is called by the @funcname.setter Adorner decoration method
The method name to be decorated by @property must have the same name as the method decorated by @funcname.setter
2. Another method can be modified, but the last method is called by a method in a class disguised as a property, and this method
Or the same as the original instantiation call
For example:
Class people:    def __init__ (self,name,age,sex,height):        self.__name = name        Self.__age = Age        Self.__sex = Sex        self.__height = height    def tell_name (self):  #看人名字        Print (self.name)    def set_name (Self,val) : #修改名字        if not isinstance (Val, str):            raise TypeError (' name must be String type ')        Self.__name = Val    def tell_info ( Self):         print ("           ---------%s info-----------           name:%s           age:%s           sex:%s           height:%s '"% ( self.__name,self.__name,self.__age,self.__sex,self.__height)) p=people (' Egon ', ' + ', ' male ', ' [+] ') p.tell_info () P.set_name (' Haiyan ')   #调用修改名字的方法p. Tell_info () # Print (p._people__name) #就可以看到了

  

Python full Stack development "the 15th" object-oriented three major features--encapsulation

Related Article

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.