[Python] class access restrictions

4.1 Access restrictions

In the previous column: Python基础, the author 面向对象introduced the properties of classes and objects in programming. According to the access level of properties, they can be divided into general properties and private properties.
Usually, in classes and objects, if a property name starts with __, it means that the property is a private property, and under normal circumstances, the property cannot be directly called or modified externally. By making the property private it is 访问限制.
Access restrictions are for the robustness of the program, making it impossible to directly modify some specific attributes externally, ensuring the normal operation of the program.
For example, if there is an attribute in a class that is used to store age, and there is a method that needs to use this age attribute, and uses this age as a divisor, if you accidentally set or enter an age of 0, it will cause a program error.
For some important attributes, if we want users to obtain or modify them, we can implement them through custom methods, such as getage and setage. Setting properties through methods allows parameter checking to avoid passing in wrong or invalid parameters.
定义私有变量

class Person:
    def __init__(self):
        self.name = 'lucy'
        self.__age = 10


p = Person()
ic(p.name)
ic(p.__age)

17:09:42|> p.name: ‘lucy’
Traceback (most recent call last):
File “E:\t1.py”, line 12, in
ic(p.__age)
AttributeError: ‘Person’ object has no attribute ‘__age’

We can see that the attributes can be obtained directly from the outside name, but the attributes cannot be obtained __age.
通过方法获取属性

from icecream import ic


class Person:
    def __init__(self):
        self.name = 'lucy'
        self.__age = 10

    def getage(self):
        return self.__age


p = Person()
ic(p.getage())

17:28:25|> p.getage(): 10

通过方法修改属性

from icecream import ic


class Person:
    def __init__(self):
        self.name = 'lucy'
        self.__age = 10

    def getage(self):
        return self.__age

    def setage(self, age):
        if isinstance(age, int) and 0 < age < 150:
            self.__age = age
        else:
            ic('输出的年龄有误,请核对!')


p = Person()
p.setage(20)
ic(p.getage())
p.setage(200)
ic(p.getage())

18:03:42|> p.getage(): 20
18:03:42|> 'The output age is wrong, please check!'
18:03:42|> p.getage(): 20

4.1.2 Packaging

In Python, encapsulation is a code organization technique that can be used to manage data and associated methods (functions) as a unit. You can control access to class member variables and protect them from unwanted modification by defining public methods in the class.
封装有以下作用:

  • Bundle data with related behavior to facilitate management and maintenance of code.
  • Hide the specific implementation details, making the code more secure and abstract.
  • Reduce code complexity and improve code readability and maintainability by exposing only limited interfaces.
  • Improved interoperability and collaboration between software modules, making the software more scalable and flexible.
    In python, private members can be emulated using a special naming convention. We can add a double underscore "__" before the name, which prevents others from accidentally accessing the member, and can only be accessed through the public methods defined in the class.
class Car:
    # 定义类私有变量
    __max_speed = 0
    __mileage = 0
 
    def __init__(self):
        # 初始化变量
        self.__max_speed = 200
        self.__mileage = 10
 
    # 定义公共方法
    def drive(self):
        print('Driving. Max speed:', self.__max_speed)
 
    # 定义getter和setter方法
    def get_max_speed(self):
        return self.__max_speed
 
    def set_max_speed(self, speed):
        self.__max_speed = speed
 
car = Car()
print(car.get_max_speed()) # 输出200
car.set_max_speed(250)
car.drive() # Driving. Max speed: 250

In the above code, the Car class defines two private variables __max_speed and __mileage, which can only be used inside the class. Then, we define a public method drive(), which is accessible outside the class, and uses getter and setter methods to manage the value of the variable __max_speed. This way, we can access the data and methods of the class through its public interface without directly accessing its private variables.

Guess you like

Origin blog.csdn.net/crleep/article/details/131373417