Encapsulation of 3 major features of Python object-oriented

Encapsulation is a major feature of object-oriented programming.

The first step of object-oriented programming-encapsulate attributes and methods into an abstract class based on responsibilities. The outside world uses the class to create objects, and then the object calls methods. The details of the object methods are encapsulated inside the class.

Simple understanding of encapsulation, that is, when designing a class, some properties and methods are deliberately hidden inside the class, so that when using this class, you cannot directly use "class object. property name" or "class object. method name ( These attributes or methods are called in the form of "parameters)", and these hidden attributes and methods can only be manipulated indirectly with unhidden class methods.

It's like using a computer. We only need to learn how to use the keyboard and mouse, and we don't need to care about how it is implemented internally, because that is what the production and designers should worry about.

Examples:

Demand design: Xiao Ming weighs 75.0 kg, and loses 0.5 kg every time he runs, and he gains 1 kg every time he eats.

class Person:
    """人类"""

    def __init__(self, name, weight):

        self.name = name
        self.weight = weight

    def __str__(self):

        return "我的名字叫 %s 体重 %.2f 公斤" % (self.name, self.weight)

    def run(self):
        """跑步"""

        print("%s 爱跑步,跑步锻炼身体" % self.name)
        self.weight -= 0.5

    def eat(self):
        """吃东西"""

        print("%s 是吃货,吃完这顿再减肥" % self.name)
        self.weight += 1

xiaoming = Person("小明", 75)
xiaoming.run()
xiaoming.eat()
xiaoming.eat()
print(xiaoming)
# 小明 爱跑步,跑步锻炼身体
# 小明 是吃货,吃完这顿再减肥
# 小明 是吃货,吃完这顿再减肥
# 我的名字叫 小明 体重 76.50 公斤

Here is another example: placing furniture.

Demand design:

  • 1. The house has a list of apartment types, total area and furniture names. The new house does not have any furniture.
  • 2. Furniture (HouseItem) has a name and floor space, among which
    • Simmons (bed) covers an area of ​​4 square meters
    • The wardrobe (chest) covers an area of ​​2 square meters
    • The table covers an area of ​​1.5 square meters
  • 3. Add the above three pieces of furniture to the house.
  • 4. When printing a house, it is required to output: a list of house type, total area, remaining area, and furniture name.

First define the furniture category:

class HouseItem:

    def __init__(self, name, area):
        """

        :param name: 家具名称
        :param area: 占地面积
        """
        self.name = name
        self.area = area

    def __str__(self):
        return "[%s] 占地面积 %.2f" % (self.name, self.area)


bed = HouseItem("席梦思", 4)
chest = HouseItem("衣柜", 2)
table = HouseItem("餐桌", 1.5)

print(bed)  # [席梦思] 占地面积 4.00
print(chest)  # [衣柜] 占地面积 2.00
print(table)  # [餐桌] 占地面积 1.50

Define the house class:

class House:

    def __init__(self, house_type, area):
        """

        :param house_type: 户型
        :param area: 总面积
        """
        self.house_type = house_type
        self.area = area

        # 剩余面积默认和总面积一致
        self.free_area = area
        # 默认没有任何的家具
        self.item_list = []

    def __str__(self):

        # Python 能够自动的将一对括号内部的代码连接在一起
        return ("户型:%s\n总面积:%.2f[剩余:%.2f]\n家具:%s"
                % (self.house_type, self.area,
                   self.free_area, self.item_list))

    def add_item(self, item):

        print("要添加 %s" % item)

my_home = House("两室一厅", 60)
my_home.add_item(bed)
my_home.add_item(chest)
my_home.add_item(table)
print(my_home)

Improve the method of adding furniture:

    def add_item(self, item):

        # 1. 判断家具面积是否大于剩余面积
        if item.area > self.free_area:
            print("%s 的面积太大,不能添加到房子中" % item.name)
            return

        # 2. 将家具的名称追加到名称列表中
        self.item_list.append(item.name)

        # 3. 计算剩余面积
        self.free_area -= item.area

In this example, the main program is only responsible for creating the house object and the furniture object. Let the house object call the add_item method to add the furniture to the house. The area calculation, remaining area, and furniture list are all encapsulated in the house class.

The encapsulation mechanism ensures the integrity of the internal data structure of the class, because users who use the class cannot directly see the data structure in the class, and can only use the data that the class allows to expose, which avoids external influence on internal data and improves The maintainability of the program.

In addition, to achieve a good encapsulation of a class, users can only access data with the help of exposed class methods, we only need to add appropriate control logic to these exposed methods, and then users can easily realize the attributes in the class. Or the unreasonable operation of the method.

Moreover, good encapsulation of classes can also improve code reusability.


The pilgrimage of programming

Guess you like

Origin blog.csdn.net/beyondamos/article/details/108215222