zoukankan      html  css  js  c++  java
  • python基础之类的特性(property)

    一 什么是特性property
    property是一种特殊的属性,访问它时会执行一段功能(函数)然后返回值。

    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
    '''
    

    注意:此时的特性arear和perimeter不能被赋值

    c.area=3 #为特性area赋值
    '''
    抛出异常:
    AttributeError: can't set attribute
    '''
    

    二、为什么要用property

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

    1、

    class People:
        def __init__(self,name,age,height,weight):
            self.name=name
            self.age=age
            self.height=height
            self.weight=weight
        @property
        def bodyindex(self):
            return self.weight/(self.height**2)
    
    
    p1=People('cobila',38,1.65,74)
    print(p1.bodyindex)
    p1.weight=200
    print(p1.bodyindex)
    

    2、

    #被property装饰的属性会优先于对象的属性被使用

    #而被propery装饰的属性,如sex,分成三种:
    # 1.property
    # 2.sex.setter
    # 3.sex.deleter

    class People:
        def __init__(self,name,SEX):
            self.name=name
            # self.__sex=SEX
            self.sex=SEX#p1.sex='male'
    
        @property
        def sex(self):
            print('------proerty---------------------->')
            return self.__sex
    
        @sex.setter
        def sex(self,value):
            print('===================》')
            # print(self,value)
            # if not isinstance(value,str):
            #     raise TypeError('性别必须是字符串类型')
            self.__sex=value  #p1.ABCDEFG='male'
        @sex.deleter
        def sex(self):
            print('delete 操作')
            del self.__sex
    
    p1=People('egon','male')
    print(p1.__dict__)
    print(p1.sex)
    # del p1.sex
    # print(p1.sex)
    

    参考链接:http://www.cnblogs.com/linhaifeng/articles/6182264.html

  • 相关阅读:
    Interview with BOA
    Java Main Differences between HashMap HashTable and ConcurrentHashMap
    Java Main Differences between Java and C++
    LeetCode 33. Search in Rotated Sorted Array
    LeetCode 154. Find Minimum in Rotated Sorted Array II
    LeetCode 153. Find Minimum in Rotated Sorted Array
    LeetCode 75. Sort Colors
    LeetCode 31. Next Permutation
    LeetCode 60. Permutation Sequence
    LeetCode 216. Combination Sum III
  • 原文地址:https://www.cnblogs.com/luchuangao/p/6743999.html
Copyright © 2011-2022 走看看