例子一:
# @property的使用
class PropertyClass(object):
@property
def score(self):
return self.__score
@score.setter
def score(self, value):
# 用来判断赋值时是否进入该函数
print("Your in score.setter")
self.__score = value
propertyExam = PropertyClass()
propertyExam.score = 100
print(propertyExam.score)
例子二:
# @property的使用
class Screen(object):
def __init__(self, width=None, height=None):
self.width = width
self.height = height
@property
def sWidth(self):
return self.width
@property
def sHeight(self):
return self.height
@sWidth.setter
def sWidth(self, width):
self.width = width
@sHeight.setter
def sHeight(self, height):
self.height = height
@property
def resolution(self):
return self.width * self.height
screen = Screen()
screen.sWidth = 1366
screen.sHeight = 768
print(screen.sWidth)
print(screen.sHeight)
# 只读属性调用
print(screen.resolution)