使用装饰器的实质是将方法伪装成属性调用,但并不是真的存在该属性。
_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'