温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

面向对象-property

发布时间:2020-06-29 04:42:36 来源:网络 阅读:294 作者:DevOperater 栏目:编程语言

1.property

1.1什么是property

property是一种特殊的属性,访问它会执行一个函数,然后返回值
特点:
1.执行函数时不需要obj.func()这样调用,直接obj.func,像调用变量一样调用函数,就可以执行一个函数
2.不能给其赋值
3.但是有@func.setter和@func.deleter装饰器放在func上,可以实现对func的设置和删除

例如:BMI值=体重(kg)÷身高^2(m)
class People:
    def __init__(self,name,weight,height):
        self.name=name
        self.weight=weight
        self.height=height
    @property
    def bmi(self):
        return self.weight / (self.height**2)

p1=People('egon',75,1.85)
print(p1.bmi)
例如:圆的周长和面积
import math
class Circle:
    def __init__(self,radius): #圆的半径radius
        self.radius=radius

    @property
    def area(self):
        return math.pi * self.radius**2 #计算面积

    @property
    def perimeter(self):
        return 2*math.pi*self.radius #计算周长

c=Circle(10)
print(c.radius)
print(c.area) #可以向访问数据属性一样去访问area,会触发一个函数的执行,动态计算出一个值
print(c.perimeter) #同上
'''
输出结果:
314.1592653589793
62.83185307179586
'''
"这里的area和perimeter不能被赋值"
c.area=3 #为特性area赋值
'''
抛出异常:
AttributeError: can't set attribute
'''

1.2为什么使用property

将一个类的函数定义为特性后,对象再去使用的时候obj.name,根本无法察觉自己的name是执行了一个函数计算出来的,这个property的使用方式遵循了统一访问的原则

ps:面向对象的封装有三种方式:
【public】
这种其实就是不封装,是对外公开的
【protected】
这种封装方式对外不公开,但对朋友(friend)或者子类(形象的说法是“儿子”,但我不知道为什么大家 不说“女儿”,就像“parent”本来是“父母”的意思,但中文都是叫“父类”)公开
【private】
这种封装对谁都不公开

python并没有在语法上内置public,protected,private,在Java中会把所有数据设置为私有的,然后提供set和get方法去设置和获取,在Python中可以通过property实现

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Foo:
    def __init__(self,val):
        self.__NAME=val #将所有的数据属性都隐藏起来

    @property
    def name(self):
        return self.__NAME #obj.name访问的是self.__NAME(这也是真实值的存放位置)

    @name.setter
    def name(self,value):
        if not isinstance(value,str):  #在设定值之前进行类型检查
            raise TypeError('%s must be str' %value)
        self.__NAME=value #通过类型检查后,将值value存放到真实的位置self.__NAME

    @name.deleter
    def name(self):
        raise TypeError('Can not delete')
f=Foo('egen')
print(f.name)

f.name="10"
print(f.name)

结果
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
egen
10

Process finished with exit code 0
f.name=10
结果
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
Traceback (most recent call last):
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 23, in <module>
    f.name=10
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 15, in name
    raise TypeError('%s must be str' %value)
TypeError: 10 must be str

Process finished with exit code 1
del f.name

结果
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
Traceback (most recent call last):
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 23, in <module>
    del f.name
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 20, in name
    raise TypeError('Can not delete')
TypeError: Can not delete

Process finished with exit code 1
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI