Python __slots__ ,@property,私有变量学习记录

使用装饰器的实质是将方法伪装成属性调用,但并不是真的存在该属性。

_Student__score根据不同解释器并不总是能正确调用__score属性,所以最后不要用。

另外,单下划线命名的变量(包括类,函数,普通变量)不能通过from module import * 导入到另外一个模块中,通过

 

import Class

Clsss._test

或者

from Class import _test

都可正常调用。Python对手贱的孩子真是毫无办法

以下是混合使用__slots__ 、@property 、__variables  的例子

class Student(object):
    __slots__ = ('__score',)
    
    @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
    
    @property
    def koufen(self):
        return 100 - self.__score

A = Student()
A.score = 99
print(A.score)
print(A.koufen)
print(A._Student__score)
print(A.__score)

 结果:

99
1
99
Traceback (most recent call last):

  File "<ipython-input-38-6c723c2ab4a4>", line 1, in <module>
    runfile('E:/test3.py', wdir='E:')

  File "D:\Anaconda2\envs\py3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "D:\Anaconda2\envs\py3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "E:/test3.py", line 32, in <module>
    print(A.__score)

AttributeError: 'Student' object has no attribute '__score'

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值