使用裝飾器的實質是將方法僞裝成屬性調用,但並不是真的存在該屬性。
_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'