面向对象之封装

封装

封装就是打包,封起来,装起来

封装数据:将数据隐藏起来这不是目的。隐藏起来然后对外提供操作该数据的接口,然后我们可以在接口附加上对该数据操作的限制,以此完成对数据属性操作的严格控制。


封装分为两个层面

第一个层面:对象能拿到类的东西,但是类能拿到对象的东西吗?

 class Foo():
     count = 0
     print(count)

     f = Foo()
     print(f.count)  # 0
     f.name = 'nick'  # 对对象进行了封装
     print(Foo.name)
第二个层面的:内部可以使用,外部不可以使用,在你需要封装的属性前面加上__
 class People():
     __love_people = 'male'
     # print('in',love_people)

     def __nawan(self):
         print('nawan')
     def __nakuaizi(self):
         print('nakuaizi')
     def __chifan(self):
         print('chifan')

     def chifan_all(self):
         self.__nawan()
         self.__nakuaizi()
         self.__chifan()


 # print('out',People.__f1)

 类的property特性

property一般用在:本来是方法,但是他应该是属性的时候,我们就应该property

class People():

    def __init__(self,height,weight):
        self.height = height
        self.weight = weight

    @property
    def bmi(self):
        return self.weight/(self.height**2)

peo = People(1.8,70)
print(peo.height)
# print(peo.bmi())
print(peo.bmi)

装饰器用法(只在Python3中使用)

class People():

    def __init__(self,height,weight):
        self.height = height
        self.weight = weight

    @property  # 获取值的时候触发,你不需要加括号使用,不能加参数
    def bmi(self):
        return self.weight/(self.height**2)

    @bmi.setter  # 在修改bmi的时候触发,必须得加参数
    def bmi(self, value):
        print(f'你已经成功修改为{value}')

    @bmi.deleter  # 在删除bmi的时候触发,不能加参数
    def bmi(self):
        print('delter')

peo = People(1.8,70)
print(peo.bmi)

print('*'*50)
peo.bmi = 50

print('*'*50)
del peo.bmi

 类与对象的绑定方法

class OldBoyStudent:  # 类的定义阶段,会运行代码(牢记)
    # 1 / 0
    school = 'oldboy'

    def __init__(self, id, name, age=15):  # (******)  # aaa是实例化的对象,自动传值  # self=stu1  # self=stu2
        self.id = id  # stu1.id = id
        self.name = name  # stu1.name = name
        self.age = age  # stu1.age = age

    def choose_course(self):  # 约定俗成为self
        # 1 / 0
        print(id(self))
        print(self.school)
        print(self.id)
        self.id += 1
        print(f'{self.name} is choosing course')


stu1 = OldBoyStudent(222222, '朱瑞星')  # 每次实例化对象的时候都会自动调用__init__方法(排在第一位的)
# OldBoyStudent.choose_course(1111)  # self = 1111
print('*' * 50)
stu1.choose_course()  # self = <__main__.OldBoyStudent object at 0x000001C5EC999860>
print(stu1.id)

# 针对类而言:choose_course里的self就是传的参数
# 针对对象而言:choose_course里的self就是对象本身
stu2 = OldBoyStudent(666666, '孔悟空', 19)  # 每次实例化对象的时候都会自动调用__init__方法(排在第一位的)
# stu2.choose_course()
print(stu2.id)

 

原文地址:https://www.cnblogs.com/legend27/p/11060186.html