码迷,mamicode.com
首页 > 编程语言 > 详细

python基础之封装

时间:2017-04-22 09:40:59      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:自己   imu   ide   ble   body   cal   异常   splay   种类   

封装概念:

property代码1

技术分享
import math
class Circle:
    def __init__(self,radius):  #圆的半径
        self.radius=radius
    @property   #添加装饰器,area=property(area)
    def area(self):
        return math.pi * self.radius**2 #计算面积

    @property   #添加装饰器,perimeter=property(perimeter)
    def perimeter(self):
        return 2*math.pi*self.radius    #计算周长
c=Circle(7)
c.radius=10
print(c.radius) #打印出圆的半径
# print(c.area()) #会报错,TypeError: ‘float‘ object is not callable,译为:float对象是不可调用的
# print(c.perimeter())    #float对象是不可调用的
print(c.area)   #表面上是一个数据属性,但这个根本上是一个函数属性,会调用上面的area函数,打印圆的面积
print(c.perimeter)  #打印圆的周长
代码片段1

property代码2

技术分享
class People:
    def __init__(self,name,age,height,weight):
        self.name=name
        self.age=age
        self.height=height
        self.weight=weight
    @property #该装饰器可以理解为bodyindex=property(bodyindex)
    def bodyindex(self):    #计算体脂
        return self.weight/(self.height**2)

p1=People(cobila,18,1.65,75)
print(p1.bodyindex)   #过轻:低于18.5,正常:18.5-23.9,过重:24-27,肥胖:28-32,非常肥胖, 高于32
p1.weight=200
print(p1.bodyindex)
代码片段2

property代码3

技术分享
class People:
    def __init__(self,name):
        self.__name=name    #self.__name

    # def tell_name(self):
    #     return self.__name
    @property
    def name(self):
        return self.__name
p1=People(cobila)
# print(p1.tell_name())
print(p1.name)  #触发name()函数的运行
# p1.name=‘egon‘    #会报错,AttributeError: can‘t set attribute
代码片段3

property代码4

技术分享
class People:
    def __init__(self,name,SEX):
        self.name=name
        self.__sex=SEX  #self.sex=‘male‘ p1.sex(相当于self.sex)=‘male‘
    @property #
    def sex(self):
        return self.__sex   #p1.__sex
    @sex.setter #修改
    def sex(self,value):    #性别是字符串类型
        # print(self,value) #
        if not isinstance(value,str):   #python没有类型限制,所以只能自己加这种类型限制
            raise TypeError("性别必须是字符串类型")
        self.__sex=value    #p1.__sex=‘male‘
    @sex.deleter    #删除
    def sex(self):
        del self.__sex #触发delete函数的运行,del p1.__sex
        # del self.sex  #这是错误的
# p1=People(‘cobila‘,‘male‘)
# print(p1.sex)
# p1.sex=‘123‘
# p1.sex = ‘female‘   #这个等式触发def sex(self,value)的运行,把female这个值传给value
# print(p1.sex)   #输出female
# p1.sex=9999999    #由于更改的不是字符串类型,所以会抛出异常
# p1=People(‘cobila‘,9999999999999999)    #这里更改的是def sex(self):下面的self.__sex

p1=People(cobila,male)  #实例化触发__init__的运行
print(p1.sex)   #输出male
# del p1.sex  #@sex.deleter一执行它(def sex(self)),del self.sex,无限递归,一直删除自己,会报错(RecursionError: maximum recursion depth exceeded)
# print(p1.sex)
代码片段4

 

python基础之封装

标签:自己   imu   ide   ble   body   cal   异常   splay   种类   

原文地址:http://www.cnblogs.com/bingabcd/p/6746725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!