python - class propert应用

Posted Anec

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python - class propert应用相关的知识,希望对你有一定的参考价值。

propert应用

#方式一:
# class Student(object):
#     def __init__(self,name,sc):
#         self.name = name
#         self.sc = sc
#
#     @property
#     def score(self):
#         return self.sc
#
#     @score.setter
#     def score(self,value):
#         if not isinstance(value, int):
#             raise ValueError(‘分数必须是整数才行呐‘)
#         if value < 0 or value > 100:
#             raise ValueError(‘分数必须0-100之间‘)
#         self.sc = value
#
#     @score.deleter
#     def score(self):
#         del self.sc

#-----------------------------------------------------------

#方式二:
class Student(object):
    def __init__(self,name,sc):
        self.name = name
        self.sc = sc

    def get_score(self):
        return self.sc

    def set_score(self,value):
        if not isinstance(value, int):
            raise ValueError(分数必须是整数才行呐)
        if value < 0 or value > 100:
            raise ValueError(分数必须0-100之间)
        self.sc = value

    def del_score(self):
        del self.sc

    score = property(get_score,set_score,del_score)

X = Student(anec,50)
print(X.__dict__)
print(X.score)
X.score = 90
print(X.score)
del X.score
print(X.__dict__)

 

以上是关于python - class propert应用的主要内容,如果未能解决你的问题,请参考以下文章

错误记录PyCharm 运行 Python 程序报错 ( PEP 8: E305 expected 2 blank lines after class or function definiti )(代

Kotlinspring boot项目中,在Idea下启动,报错@Configuration class 'BugsnagClient' may not be final.(示例代(代

隔代无法继承

kafkakafka DefaultRecordBatch. The older message format classes only support conversion from class(代

诡异的JVM永久代溢出

Android 逆向Dalvik 函数抽取加壳 ( 类加载流程分析 | Class.cpp#findClassNoInit 函数 | DexFile.cpp#dexFindClass 函数分析 )(代