栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Python

python把方法变成属性调用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python把方法变成属性调用

# encoding: utf-8
# @file: property.py
# @software: PyCharm
# @time: 2022/8/9 23:40
# @desc: 方法变成属性调用
"""
装饰器(decorator)可以给函数动态加上功能,对于类的方法,装饰器一样起作用。
Python内置的@property装饰器就是负责把一个方法变成属性调用的:
@property:把一个getter方法xxx(无入参)变成属性
@xxx.setter:负责把一个setter方法(有入参)变成属性赋值
"""
class Screen(object):

    # 读属性
    @property
    def width(self):
        return self.value_width

    # 写属性
    @width.setter
    def width(self, value):
        self.value_width = value

    @property
    def height(self):
        return self.value_height

    @height.setter
    def height(self, value):
        self.value_height = value

    @property
    def resolution(self):
        return self.value_height * self.value_width


if __name__ == '__main__':
    s = Screen()
    # 方法s.width()只能以属性来赋值
    s.width = 3
    s.height = 4
    # 方法s.width()只能能属性来调用了
    print(s.width, '---', s.height)
    assert s.resolution == 1, '错误,3 * 4 != 1'


#######################################################
# 3 --- 4
# Traceback (most recent call last):
#   File "D:studypri_testproperty.py", line 45, in 
#     assert s.resolution == 1, '错误,3 * 4 != 1'
# AssertionError: 错误,3 * 4 != 1
转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1038594.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号