An Intensive Introduction to the Attributes of Classes in Python


foreword

The attributes   introduced in this article are the same as those mentioned in the previous blogclass attributes and instance attributesdifferent . The previously introduced propertieswill return the stored value, while the attributes to be introduced in this article areis a special property whose value is computed when accessed. Additionally, this property can alsoAdd security protection mechanism for attributes


1. Create properties for calculation

  In Python, you can pass @property (decorator)Convert a method to a property,therebyImplement properties for computation. After converting the method to a property, you canAccess methods directly by method name,andNo need to add a pair of parentheses "()", which makes the code more concise.

insert image description here

The syntax for creating properties for calculations   via @property is as follows:

@property
def methodname(self):
    block

Parameter description :

  • methodname : Used to specify the method name, generally starting with a lowercase letter.This name will end up being the name of the created property
  • self : a required parameter, representing an instance of the class.
  • block : method body, the specific function implemented. In the method body, it usually ends with a return statement, which is used to return the calculation result.

  For example, define a rectangle class, define two instance properties in the _ _ init _ _ () method, then define a method to calculate the area of ​​a rectangle, and apply @property to convert it into a property, and finally create an instance of the class, and To access the converted properties, the code is as follows:

class Rect:
    def __init__(self, width, height):
        self.width = width  # 矩形的宽
        self.height = height  # 矩形的高
    @property  # 将方法转换为属性
    def area(self):  # 计算矩形面积的方法
        return self.width * self.height  # 返回矩形的面积
rect = Rect(10, 20)  # 创建类的实例
print('矩形的面积为:', rect.area)  # 输出属性的值

  After running the above code, the result is as follows:

矩形的面积为: 200

注意:通过 @property 转换后的属性不能重新赋值,如果对其重新赋值,将会报错如下图所示。

insert image description here


2. Add security protection mechanism for attributes

  In Python, by default, class attributes or instances createdcan be modified outside the class, if you want to restrict it from being modified outside the class, you can set it as private, but after setting it as private, you cannot directly get its value through the instance name + attribute name outside the class. If you want to create acan read but not modifyproperties, thenRead-only properties can be implemented using @property.
  For example, create a TV program class TvShow, and then create a show attribute to display the currently playing TV program. The code and execution results are shown in the following figure:

insert image description here

  The show attribute created by the above method is read-only, try to modify the value of this attribute, and then get it again. An error will be reported as shown in the following figure:

insert image description here

  Not only can a property be set to read-only through the property, but theInterceptors can be set for attributes,Right nowProperties are allowed to be modified, but certain constraints need to be followed when modifying. For example, some changes are made to the above code to allow users to modify on-demand programs, but only one of the specified TV series can be selected. The code looks like this:

class TvShow:  # 定义电视节目类
    list_show = ['县委书记', '红旗渠', '安居', '幸福里的春天', '狂飙']
    def __init__(self, show):
        self.__show = show
    @property  # 将方法转换为属性
    def show(self):  # 定义show()方法
        return self.__show  # 返回私有属性的值
    @show.setter  # 设置setter方法,让属性可修改
    def show(self, value):
        if value in TvShow.list_show:
            self.__show = '您选择了《{}》,稍后将播放'.format(value)
        else:
            self.__show = '您点播的电视剧不存在'
tvshow = TvShow('狂飙')  # 创建类的实例
print('正在播放:', tvshow.show)  # 获取属性值
print('您可以从{}中选择要播放的电视剧'.format(tvshow.list_show))
tvshow.show = '红旗渠'  # 修改属性值
print(tvshow.show)  # 获取属性值

  The running results are as follows:

insert image description here

  If you change the 'Red Flag Canal' in the penultimate line of the code to 'the name of the people', the following effect will be displayed after running:

insert image description here

Guess you like

Origin blog.csdn.net/2201_75641637/article/details/129503486