美文网首页
python基础 -- property

python基础 -- property

作者: fada492daf5b | 来源:发表于2018-01-24 14:11 被阅读0次

1. 作用

把函数变成属性,同时可以对属性进行检查

2. 操作

# property
# getter, setter

# 设定属性
# 一般情况
# class Student(object):

#     def __init__(self, name, score):
#         self.__name = name  # __value 私有变量
#         self.__score = score # 不要在外部访问,don't do that

#     def get_name(self):
#         return self.__name

#     def get_score(self):
#         return self.__score

#     def set_score(self, value):
#         if not isinstance(value, int):
#             raise ValueError('score must be an integer!')
#         if value < 0 or value > 100:
#             raise ValueError('score must between 0 ~ 100')
#         self.__score = value

# s = Student('Tommy', 76)
# print('{}-{}'.format(s.get_name(), s.get_score()))
# s.set_score(90)
# print('{}-{}'.format(s.get_name(), s.get_score()))

# 加上property
# score()方法变成属性

class Student(object):
    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    @property
    def name(self):
        return self.__name

    @property
    def score(self):
        return self.__score
    
    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100')
        self.__score = value

s = Student('Tommy', 76)
print('{}-{}'.format(s.name, s.score))
s.score = 90
print('{}-{}'.format(s.name, s.score))
# s.name = 'Laura' 只读属性

相关文章

  • python基础 -- property

    1. 作用 把函数变成属性,同时可以对属性进行检查 2. 操作

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • 2018-02-05

    python @property装饰器

  • python @property

    参考 Python进阶之“属性(property)”详解 - Python - 伯乐在线

  • Python中property中的小坑

    刚刚了解了python中的@property的使用,property本质是python中的一个内置修饰器。使用大概...

  • property, getter, setter and del

    http://www.runoob.com/python/python-func-property.htmlhtt...

  • python 中的动态属性和特性(Property)

    标题:property用法介绍。 实战: 这所有的python基础语法进阶语法都是应用于我所写的一个博客教程 博客...

  • Python property

    Question 我们一般对属性的的操作主要有2个,访问和修改。看个例子。 我们叫这种使用属性的方式叫点模式(我自...

  • python @property

    1.描述符 我们首先要搞懂描述符(Descriptor)是什么. 1.1 描述符定义 只要类中有__get__()...

  • Python @property

    以下内容来自万能的互联网... 首先教材上的@property 可以将一个方法的调用变成“属性调用”,主要用于帮助...

网友评论

      本文标题:python基础 -- property

      本文链接:https://www.haomeiwen.com/subject/qmcuaxtx.html