Python learning _day26_ Object-oriented encapsulation

Source: Internet
Author: User

1. Private properties

(1) Dynamic properties

Hides the property in Python, starting with a double underscore. Names that begin with all double underscores in a class, such as __x, are automatically formed: the form of the _ Class name __x. The characteristics of this automatic deformation are:

  A. The __x defined in a class can only be used internally, such as self.__x, and the result of the transformation is referenced. B. This distortion is in fact an external deformation, which cannot be accessed externally by the name __x. C. 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 a property that begins with a double glide line is inherited to a subclass, the subclass cannot be overwritten.

classTeacher:def __init__(SELF,NAME,PSWD): Self.name=name self.__pswd=pswd#Private Properties    deffunc (self):Print(self.)__pswd) Alex=teacher ('Alex','3714') Alex.func ()# Print (alex.__pswd) #私有属性不可以通过此方式查看Print(ALEX._TEACHER__PSWD)#How private properties are viewed externally: _teacher__pswd storage

(2) Static properties

The way to privatize is also to double-underline the attribute name, which can only be used internally, and externally viewed in the same way as dynamic properties.

classTeacher:__identifier='Teacher'                                     #private static Property    def __init__(self,name,pwd): Self.name=name self.__pwd=pwd#Private Properties    deffunc (self):Print(self.)__pwd, Teacher.__identifier)Print(Teacher._teacher__identifier)#View the static property method outsideAlex=teacher ('Alex','1234') Alex.__a='AAA'                                                 #externally defined, and does not form privatization, __A is a valid normal variable namePrint(Alex.)__dict__)#View the dynamic property dictionary with the result: {' name ': ' Alex ', ' _teacher__pwd ': ' 1234 ', ' __a ': ' AAA '}

Point of issue summary:

(a). This mechanism also does not really restrict our direct access to properties from the outside, knowing that the class name and property name can be spelled out by name: _ Class Name __ property, and then you can access it, such as A._a__n.

(b). " The __ property "Morph to" _ Class name __ Property "takes effect only within the class, after the defined approximate privatisation assignment operation, does not deform, for the normal assignment process.

2. Private methods

 The privatization method can also be used only within the class, and some of the return values of the methods are used only as intermediate results and may be privatized, as in the following example:

classTeacher:def __init__(self,name,pwd): Self.name=name self.__pwd=pwd#Private Properties    def __func(self):#Private Methods        returnHash (self.__pwd)    defLogin (Self,password):returnhash (password) ==self.__func() Alex=teacher ('Alex','1234') ret=alex.login ('2234')Print(ret)#the output is: False

In inheritance, the parent class can define a method as private if it does not want the child class to overwrite its own method.

classFoo:def __JINGHONG_SB(self):#变形为:_FOO__JINGHONG_SB        Print('Foo')classSon (Foo):def __JINGHONG_SB(self):#变形为:_SON__JINGHONG_SB        Print('Son')    deffunc (self): self.__JINGHONG_SB()#变形为:_SON__JINGHONG_SB,son=Son () son.func ()#The result: son

3. Property method

 When you implement a method in a class, you take a look at the properties of the class, and the methods in the class look like properties rather than methods. The following example:

#例1:
ClassPerson :def __init__(self,name,height,weight): Self.name=name self.__height=height self.__weight=Weight @propertydefBMI (self):returnSelf.__weight/(self.__height**2) Jinghong= Person ('Kagehiro', 1.8,94)Print(JINGHONG.NAME,JINGHONG.BMI)#output Result: Kagehiro 29.012345679012345

 

#Example 2:ImportMathclassCircle:def __init__(Self,radius): Self.radius=radius @propertydefArea (self):returnMath.PI * self.radius**2#Calculate Area@propertydefperimeter (self):return2*math.pi*self.radius#Calculate PerimeterC=circle (10)Print(C.radius)Print(C.area)#You can access the area as you would access the Data property, triggering the execution of a function that dynamically calculates a valuePrint(C.perimeter)#You can access the area as you would access the Data property, triggering the execution of a function that dynamically calculates a value

After the function of a class is defined as an attribute, when the object is reused, it is impossible to obj.name that its name is executed and then computed, and that the use of this feature follows the principle of uniform access. The above cannot be changed by assigning values to Jinghong.bmi, C.area, C.perimeter. A static property is the nature of the implementation of the Get,set,delete three methods, the concrete example is as follows:

classShop:discount= 0.75def __init__(self,name,price): Self.name=name self.__price=Price @property    defPrice (self):returnSelf.__price*shop.discount @price. Setter    defPrice (self,new_price): Self.__price=new_price @price. DeleterdefPrice (self):delSelf.__priceApple= Shop ('Apple', 5)Print(Apple.price)#Get product pricePrint(Apple.__dict__)#output: {' name ': ' Apple ', ' _shop__price ': 5}Apple.price = 6#revise the original price of the productPrint(Apple.price)Print(Apple.__dict__)#output: {' name ': ' Apple ', ' _shop__price ': 6}delApple.price#Delete Item PricePrint(Apple.__dict__)#output: {' name ': ' Apple '}
Note: The aaa.setter,aaa.deleter can only be defined after the property AAA defines the properties, as in the previous example and the property method names need to be the same as price.
4, Classmethod and Staticmethod
  (1) Common method: You must pass an object to use the properties of the object and the properties of the class
class A:     def __init__ (self,name):         = name    def func (self):                                 #普通方法,selffor formal parameter        print (Self.name)
  (2) class method (Classmethod): you must pass a class that does not need to use the properties of the object, but you can use the properties of the class
class A:     ' a '     @classmethod    def Class_method (CLS):                          # class method, CLS represents class        Print (Cls.role) A.class_method ()                                     # Output Result: Class A name. Method name () Call

(3) static method (Staticmethod): No arguments must be passed, the method does not need to use the properties of the object and the properties of the class

class Staticmethod_demo ():     ' Dog '     @staticmethod    def func ():                                   # static method, no parameter        print required ("a") Staticmethod_demo.func ()                          #  Invocation mode: Class name. Method Name ()
Usage: It is not possible to use Staticmethod to decorate a function when it is not possible to place functions independently of the class using object-oriented programming, and this function does not need to depend on the properties of the object and the properties of the class. 

Python learning _day26_ Object-oriented encapsulation

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.