One, Package
Package
Hides the properties and implementation details of an object, providing public access only to the outside.
Benefits
1. Isolate the changes;
2. easy to use;
3. Improve reusability;
4. Improve safety;
"Encapsulation principle"
1. Hide the content that does not need to be provided externally;
2. Hide the properties and provide public access to them.
private variables and private methods
Hide a property (set to private) in Python, starting with a double underscore
Private Variables
The names of all double underscores in the #其实这仅仅这是一种变形操作 # class, such as __x, are automatically formed: the form of the __x: Class A: __n=0 #类的数据属性就应该是共享的, but syntactically it is possible to set the data property of the class to private, such as __n, Will deform to _a__n def __init__ (self): self.__x=10 #变形为self. _a__x def __foo (self): #变形为_A__foo print (' from A ') def Bar (self): Self.__foo () #只有在类内部才可以通过__foo的形式访问到. #A. _a__n is accessible, that is, this operation is not strictly restricting external access, It's just a grammatical distortion.
Features of this automatic deformation:
1. Defined in the class __x can only be used internally, such as Self.__x, which is referred to as the result of deformation .
2. This deformation is in fact the external deformation , the outside is not accessible by the name __x.
3. The __x defined in the subclass does not overwrite the __x defined by the parent class, because the subclass is formed: The subclass name is __x, and the parent class is formed: The parent class name __x, that is, when the double-glide line begins with a property that inherits to the subclass, the subclass cannot be overwritten.
The problems to be aware of in this deformation are:
1. This mechanism also does not really restrict our direct access to properties from the outside, know the class name and property name can be spelled out name: _ Class Name __ property, then you can access, such as A._a__n
2. The process of deformation occurs only once in the definition of the class, the assignment operation after the definition, does not deform
Private Methods
3. In inheritance, the parent class can define a method as private if it does not want the subclass to overwrite its own method
#正常情况 >>> class A: ... Def fa (self): ... Print (' from A ') ... def test (self): ... SELF.FA () ... >>> class B (A): ... Def fa (self): ... Print (' from B ') ... >>> b=b () >>> b.test () from B #把fa定义成私有的, i.e. __fa>>> class A: ... def __fa (self): #在定义时就变形为_A__fa ... Print (' from A ') ... def test (self): ... SELF.__FA () #只会与自己所在的类为准, that is, call _a__fa ... >>> class B (A): ... def __fa (self): ... Print (' from B ') ... >>> b=b () >>> b.test () from A
Encapsulation and extensibility
Encapsulation is a clear distinction between inside and outside, so that the class implementation can modify the contents of the package without affecting the external caller's code, while the external use of the user only know an interface (function), as long as the interface (function) name, parameters, the user's code will never need to change. This provides a good basis for cooperation--or, as long as the interface's underlying contract is unchanged, the code changes anthias.
#类的设计者class: def __init__ (self,name,owner,width,length,high): self.name=name Self.owner=owner self.__width=width self.__length=length self.__high=high def tell_area (self): #对外提供的接口, Hides the internal implementation details, at this point we want to ask for the area return self.__width * self.__length# users >>> r1=room (' bedroom ', ' Egon ', 20,20,20) > >> R1.tell_area () #使用者调用接口tell_area # Designer of the class, easy to extend the functionality, and the user of the class does not need to change their own code class: def __init__ (Self,name, Owner,width,length,high): self.name=name self.owner=owner self.__width=width self.__length= Length Self.__high=high def tell_area (self): #对外提供的接口, hide the internal implementation, at this time we want to ask for the volume, the internal logic has changed, only need to repair the following line can be very simple to achieve, And the external call is not aware, still using the method, but the function has changed to return self.__width * self.__length * self.__high# for those who are still using the Tell_area interface, No need to change your code, you can use the new features >>> R1.tell_area ()
Property Properties
What is attribute property
property is a special attribute that performs a function (function) and then returns a value when it is accessed
Example one: BMI (BMI is calculated, but obviously it sounds like an attribute rather than a method, if we make it an attribute that is easier to understand) adult BMI: too light: Less than 18.5 normal: 18.5-23.9 overweight: 24-27 obese: 28-32 very obese, Above 32 body mass index (BMI) = weight (kg) ÷ height ^2 (m) ex:70kg÷ (1.75x1.75) =22.86
Example One
Class people: def __init__ (self,name,weight,height): self.name=name self.weight=weight Self.height=height @property def BMI (self): return self.weight/(self.height**2) p1=people (' Egon ', 75,1.85) print (P1.BMI)
View Code
Import MathClass Circle: def __init__ (Self,radius): #圆的半径radius Self.radius=radius @property def Area (self): return Math.PI * self.radius**2 #计算面积 @property def perimeter (self): return 2*math.pi* Self.radius #计算周长c =circle Print (C.radius) print (C.area) #可以向访问数据属性一样去访问area, triggering the execution of a function that dynamically calculates a value of print ( C.perimeter) #同上 ' output: 314.159265358979362.83185307179586 '
example two: circumference and area of a circle
#注意: The attribute area and perimeter cannot be assigned c.area=3 #为特性area赋值 ' ' Throws an exception: Attributeerror:can ' t set attribute '
Why do you use property
After the function of a class is defined as an attribute, when the object is Obj.name, it is impossible to realize that its name is executed by a function and then computed, and that the use of this feature follows the principle of uniform access .
Besides, look at the
PS: Object-oriented encapsulation There are three ways: "Public" this is actually not encapsulated, is open to the external "protected" This packaging method is not public, but to friends (friend) or sub-class (the image is "son", but I do not know why people do not say "daughter", like "Parent" is meant to be "parents", but Chinese is called "father") public "private" this package is not open to anyone
Python does not have the syntax to build three of them into its own class mechanism, in C + + will generally be all the data is set to private, and then provide set and get method (interface) to setup and fetch, in Python through the property method can be implemented
Class Foo: def __init__ (self,val): self.__name=val #将所有的数据属性都隐藏起来 @property def NAME (self): Return self.__name #obj. Name accesses the Self.__name (which is also where the real value is stored) @name. Setter def NAME (self,value): if not Isinstance (VALUE,STR): #在设定值之前进行类型检查 raise TypeError ('%s must be str '%value) Self.__name=value # After the type check, the value is stored in the real location self.__name @name. Deleter def NAME: raise TypeError (' Can not delete ') F =foo (' Egon ') print (f.name) # f.name=10 #抛出异常 ' typeerror:10 must is str ' del f.name #抛出异常 ' typeerror:can not delete '
The nature of a static property is to implement the Get,set,delete three methods
Class Foo: @property def aaa (self): print ("Run me when get") @AAA. Setter def aaa (Self,value): Print ("Run Me When set") @AAA. Deleter def AAA (self): print (' Run me when delete ') # Aaa.setter,aaa.deleterf1=foo () F1 can be defined only after the property AAA defines the properties. Aaaf1.aaa= ' AAA ' del F1. Aaa
View Code
Class Foo: def get_aaa (self): print (' Run me when get ') def set_aaa (self,value): print (' Run me When set ') def delete_aaa (self): print (' Run me when delete ') Aaa=property (GET_AAA,SET_AAA,DELETE_AAA) # The built-in property has three parameters corresponding to the Get,set,delete one by one f1=foo () F1. Aaaf1.aaa= ' AAA ' del F1. Aaa
View Code
How to use it?
Class Goods: def __init__ (self): # original price self.original_price = # discount self.discount = 0.8 @ Property def Price: # Actual prices = Price * Discount new_price = self.original_price * Self.discount return NEW_PRI Ce @price. Setter def price (self, value): self.original_price = value @price. deleter def Price (self): del self.original_priceobj = Goods () obj.price # get commodity prices Obj.price = $ # Modify the original price print ( Obj.price) del obj.price # Delete Item original price
Classmethod
Class Classmethod_demo (): role = ' dog ' @classmethod def func (CLS): print (Cls.role)
Classmethod_demo.func ()
Staticmethod
Class Staticmethod_demo (): role = ' dog ' @staticmethod def func (): print ("When normal method is used")
Staticmethod_demo.func ()
Python develops an object-oriented foundation: encapsulation