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

Python查漏补缺03==>@property函数的用法

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

Python查漏补缺03==>@property函数的用法

提示:基础知识查漏补缺

✅@property函数的用法

既要保护类的封装特性,又要让开发者可以使用“对象.属性”的方式操作操作类属性,除了使用 property() 函数,Python 还提供了 @property 装饰器。通过 @property 装饰器,可以直接通过方法名来访问方法,不需要在方法名后添加一对“()”小括号。

定义一个Person类,并操作类中的私有属性:name、age、sex

  • 代码示例1如下:
class Person:

    def __init__(self, name, age, sex):
        self._name = name
        self._age = age
        self._sex = sex

    def get_name(self):
        # print(f"My name is {self._name}")
        return self._name

    def get_age(self):
        return self._age

    def get_sex(self):
        return self._sex

if __name__ == "__main__":
    p = Person('Kele_Oct', 28, 'male')
    print(f"This is {p.get_name()}."
          f"nHe is {p.get_age()} years old",
          f"nHe is a {p.get_sex()}")

运行结果:

This is Kele_Oct.
He is 28 years old 
He is a male

定义一个Person类,并定义用 @property 修饰的方法操作类中的 name、age、sex 私有属性

  • 代码示例2如下:
class Person:

    def __init__(self, name, age, sex):
        self._name = name
        self._age = age
        self._sex = sex

    @property
    def get_name(self):
        # print(f"My name is {self._name}")
        return self._name

    @property
    def get_age(self):
        return self._age

    @property
    def get_sex(self):
        return self._sex

if __name__ == "__main__":
    p = Person('Kele_Oct', 28, 'male')
    print(f"This is {p.get_sex} ")
    print(f"He is {p.get_age} years old")
    print(f"He is a {p.get_sex}")

运行结果:

This is male 
He is 28 years old
He is a male
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980329.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

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