Python study notes (11): object-oriented packaging

1. The meaning of encapsulation

  • Put attributes and methods together as a whole, and then deal with it by instantiating objects;

  • Hide the internal implementation details, only need to interact with the object and its attributes and methods;

  • Add 2. Access authority control to the attributes and methods of the class.

2. Modify the value of the private attribute

  • If two underscores'__' are added in front of the attribute and method name, it indicates that the attribute and method are private permissions
  • Use get_xxx() and set_xxx() methods to get and modify private attribute values

The sample code is as follows:

# 定义一个Master类
class Master(object):
    def __init__(self):
        self.formula = "古法煎饼果子配方"
        self.__sal = 10000

    def make_cake(self):
        print("[古法]按照{}制作一份煎饼果子".format(self.formula))

    # 获取私有属性值
    def get_sal(self):
        return self.__sal

    # 接收参数,修改私有属性值
    def set_sal(self, sal):
        self.__sal = sal

# 定义一个子类Prentice,继承了父类Master
class Prentice(Master):
    pass

# 实例化一个子类对象crystal
crystal = Prentice()
crystal.make_cake()

# 获取私有属性值
print(crystal.get_sal())

The output is as follows:

[古法]按照古法煎饼果子配方制作一份煎饼果子
10000

 

Guess you like

Origin blog.csdn.net/weixin_44679832/article/details/114341060