封装

封装介绍

封装:面向对象三大特征 最核心 的一个特性

封装 <=> 整合

将封装的属性进行隐藏操作

1.如何隐藏:在属性名前加__前缀,就会实现一个对外隐藏属性效果

该隐藏需要注意的问题:

I:在类外部无法直接访问双下滑线开头的属性,但知道了类名和属性名就可以拼出名字:_类名__属性,然后就可以访问了,如Foo._A__N,所以说这种操作并没有严格意义上地限制外部访问,仅仅只是一种语法意义上的变形。

class Foo:
    __x = 1  # _Foo__x

    def __f1(self):  # _Foo__f1
        print('from test')


print(Foo.__dict__)     # {'__module__': '__main__', '_Foo__x': 1, '_Foo__f1': <function Foo.__f1 at 0x00C683D0>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None}
print(Foo._Foo__x)      # 1
print(Foo._Foo__f1)     # <function Foo.__f1 at 0x00C683D0>

II:这种隐藏对外不对内,因为__开头的属性会在检查类体代码语法时统一发生变形

class Foo:
    __x = 1  # _Foo__x = 1

    def __f1(self):  # _Foo__f1
        print('from test')

    def f2(self):
        print(self.__x) # print(self._Foo__x)
        print(self.__f1) # print(self._Foo__f1)

# print(Foo.__x)        # AttributeError: type object 'Foo' has no attribute '__x'
# print(Foo.__f1)       # AttributeError: type object 'Foo' has no attribute '__f1'
obj=Foo()               # 1
obj.f2()                # <bound method Foo.__f1 of <__main__.Foo object at 0x0143B070>>
class Foo:
    __x = 1  # _Foo__x = 1

    def __f1(self):  # _Foo__f1
        print('from test')

    def f2(self):
        print(self.__x) # print(self._Foo__x)
        print(self.__f1) # print(self._Foo__f1)

Foo.__y=3
print(Foo.__dict__)     # {'__module__': '__main__', '_Foo__x': 1, '_Foo__f1': <function Foo.__f1 at 0x033A8418>, 'f2': <function Foo.f2 at 0x033A83D0>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, '__y': 3}
print(Foo.__y)          # {'__module__': '__main__', '_Foo__x': 1, '_Foo__f1': <function Foo.__f1 at 0x033A8418>, 'f2': <function Foo.f2 at 0x033A83D0>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, '__y': 3}
class Foo:
    __x = 1  # _Foo__x = 1

    def __init__(self, name, age):
        self.__name = name
        self.__age = age


obj = Foo('egon', 18)
print(obj.__dict__)           # {'_Foo__name': 'egon', '_Foo__age': 18}
# print(obj.name, obj.age)        # AttributeError: 'Foo' object has no attribute 'name'

为何要隐藏

I:隐藏数据属性"将数据隐藏起来就限制了类外部对数据的直接操作,然后类内应该提供相应的接口来允许类外部间接地操作数据,接口之上可以附加额外的逻辑来对数据的操作进行严格地控制:

# 设计者:egon
class People:
    def __init__(self, name):
        self.__name = name

    def get_name(self):
        # 通过该接口就可以间接地访问到名字属性
        # print('小垃圾,不让看')
        print(self.__name)

    def set_name(self,val):
        if type(val) is not str:
            print('小垃圾,必须传字符串类型')
            return
        self.__name=val

# 使用者:王鹏
obj = People('egon')
# print(obj.name) # 无法直接用名字属性
# obj.set_name('EGON')
obj.set_name(123123123)
obj.get_name()
# II、隐藏函数/方法属性:目的的是为了隔离复杂度

装饰器

装饰器是在不修改被装饰对象源代码以及调用方式的前提下为被装饰对象添加

property是一个装饰器,是用来绑定给对象的方法伪造成一个数据属性

# 新功能的可调用对象
# print(property)

 

案例

"""
成人的BMI数值:
过轻:低于18.5
正常:18.5-23.9
过重:24-27
肥胖:28-32
非常肥胖, 高于32
  体质指数(BMI)=体重(kg)÷身高^2(m)
  EX:70kg÷(1.75×1.75)=22.86
"""
# 案例1:
class People:
    def __init__(self, name, weight, height):
        self.name = name
        self.weight = weight
        self.height = height

    # 定义函数的原因1:
    # 1、从bmi的公式上看,bmi应该是触发功能计算得到的
    # 2、bmi是随着身高、体重的变化而动态变化的,不是一个固定的值
    #    说白了,每次都是需要临时计算得到的

    # 但是bmi听起来更像是一个数据属性,而非功能
    @property
    def bmi(self):
        return self.weight / (self.height ** 2)


obj1 = People('egon', 90, 1.50)
# print(obj1.bmi())

obj1.height = 1.60
# print(obj1.bmi())

print(obj1.bmi)


# 输出:
35.15624999999999
egon
# 案例2:
class People:
    def __init__(self, name):
        self.__name = name

    # @property
    def get_name(self):
        return self.__name

    def set_name(self, val):
        if type(val) is not str:
            print('必须传入str类型')
            return
        self.__name = val

    def del_name(self):
        print('不让删除')
        # def self.__name

    name11 = property(get_name, set_name, del_name)


obj1 = People('egon')
# print(obj1.get_name())
print(obj1.get_name())


obj1.set_name('xxq')
print(obj1.get_name())
obj1.del_name()


# 输出:
egon
xxq
不让删除
egon
# 案例三:
class People:
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):  # obj1.name
        return self.__name

    @name.setter
    def name(self, val):  # obj1.name='EGON'
        if type(val) is not str:
            print('必须传入str类型')
            return
        self.__name = val

    @name.deleter
    def name(self):  # del obj1.name
        print('不让删除')
        # del self.__name


obj1 = People('egon')
# 人正常的思维逻辑
print(obj1.name)  #
# obj1.name=18
# del obj1.name


# 输出:
egon
 

思维导图(点击链接

原文地址:https://www.cnblogs.com/zhww/p/12984048.html