1. What is encapsulation?
In a program, encapsulation is an abstraction of a concrete object
To put it simply: hide some parts (privatize), and you can't see other parts of the program (there's no way to call them directly)
Privatization: privatize the features or some methods in the class so that they cannot be used directly by the outside
2. Benefits of packaging
- Protect privacy - hide what you don't want the outside world to know
- Isolate complexity ---- hide the complex implementation in the program - > provide a simple interface [method] to use the privatized content
- Improve code robustness
- Add necessary judgment according to actual needs
3. How to package
- Generally, the property is privatized and the corresponding set and get methods are provided for the property
- Add two underscores before the attribute name to privatize it
Why privatization?
- It can be called directly or modified at will
- After modification, it does not meet the needs of real life – > bug – > it cannot be modified by the outside world at will
- In short, add a condition to judge before modifying, and let you modify only when the conditions are met
class Student: def __init__(self, name, age, sex): self.name = name # self.age = age self.__age = age # Add two underscores privatization self.sex = sex def main(): stu = Student("Tricky way", 18, 'male') print(stu.name) # print(stu.age) # print(stu.__age) # It can also be modified externally at will stu.age = -10 # It does not meet the needs of real life -- > bug -- > and cannot be modified by the outside world at will print(stu.age) if __name__ == '__main__': main()
After privatization, it cannot be called or modified through attributes! But it needs to be called and modified
Therefore, it is necessary to provide a simple interface for external acquisition
-
Provide the interface for assignment:
- The assignment is performed by the outside world. When it needs to be called by the outside world, the value is passed in, and the assignment interface needs to have a formal parameter
- Pseudo code of assignment method
def set_Field name(self, Formal parameter representing field name): if Conditions: self.__Field name = ?? elif condition: self.__Field name = ?? else: self.__Field name = Formal parameter representing field name #(or write according to the actual needs under if|elif)
-
Interface to provide values:
- The outside world only wants to obtain the value of this field and does not want to transfer the value. The value interface needs to have a return value
- Pseudo code of value taking method
#Pseudo code def get_Field name(self): return self.__Field name
Privatization encapsulates complete code
class Student: def __init__(self, name, age, sex): self.name = name # self.__age = age # Because during initialization, it is also assigned by the outside world, # Therefore, during initialization, it is also necessary to determine the rationality of the data and then assign values # Because judging the rationality of data has been encapsulated into a method, you can call the assignment method directly self.set_age(age) self.sex = sex def set_age(self, age): # Logical judgment can be added according to the actual needs of life if age < 0: # Set default values self.__age = 0 else: self.__age = age def get_age(self): return self.__age def main(): stu = Student("Tricky way", 18, 'male') stu_age = stu.get_age() print(stu_age) # Call the set interface stu.set_age(-10) stu_age = stu.get_age() print(stu_age) # The eigenvalues of objects are dynamically assigned if __name__ == '__main__': main()
set and get do not necessarily appear in pairs. They are written as required
4. Attribute get and set methods
- Attributiveization ----- > it can be called outside as if it had not been encapsulated
- Property: object Attribute name
- Method invocation: object Method name ()
- After the get and set methods are attributed - the format of calling is similar to that of calling attributes directly
How to attribute?
- Attribute the get method - > a decorator @ property provided by the system
- Attribute set method - > a setter decorator created on the basis of attribute get method - > attribute set method - > format: @ get method name setter
[for details of decorators, see] An artifact for modifying the functions of other functions -- python decorator
Code sample
class Person: def __init__(self, name, age, sex): # These characteristics are called the properties of the object self.name = name self.age = age # self.set_sex(sex) # After attributiveization, the value should be assigned in the way of attribute # self.set_sex = sex # Modify method name self.sex = sex # # @property # def get_sex(self): # return self.__sex @property def sex(self): return self.__sex # @get_sex.setter # def set_sex(self, sex): # if sex != "Man" and sex= "Female": # self.__sex = "male" # else: # self.__sex = sex @sex.setter def sex(self, sex): if sex != "male" and sex != "female": self.__sex = "male" else: self.__sex = sex # Get the properties of the object outside the class p = Person("Tricky way", 18, "male") # How to get properties: object Attribute name print(p.name) # # Call get method directly # value = p.get_sex() # print(value) # Call after attributiveization -- "can only be called by attributiveization # value = p.get_sex # After attribute, it is equivalent to get_sex()() is equivalent to "male" () = = "error TypeError: 'str' object is not callable # print(value) # After attributiveization, the modification of the attribute is mapped back to the modification or acquisition of the attribute as before encapsulation # Assign values to normal attributes p.name = "Tutu" # Assign value to privatization attribute # p.set_sex("female") # # Assign value after attribute # p.set_sex = "female" # print(p.get_sex) p.sex = "female" print(p.sex)
Because the general field name is not decorated with set and get, it is usually named directly as the field name when naming the get method and set method