class Rectangle:
def __init__(self,radius=0):
self.line = line
def getArea(self):
return self.line * 2
def getLine(self):
return self.line
def setLine(self,value):
# 加强校验
if not isinstance(value,(int,float)):
raise ValueError("wrong type.")
self.line = float(value)
rect = Rectangle()
rect.line= "abc" # 这样不加控制就有安全问题
rect.area() # "abcabc"
rect.setLine('abc') # ValueError: wrong type.
# 但这样调用又会麻烦,能不能像rect.line ,rect.line='xx' 这样操作
# property(fget=None, fset=None, fdel=None, doc=None)
class Rectangle:
def __init__(self,radius=0):
self.radius = radius
def getArea(self):
return self.radius * 2
def getLine(self):
return self.radius
def setLine(self,value):
# 加强校验
if not isinstance(value,(int,float)):
raise ValueError("wrong type.")
self.radius = float(value)
line = property(getLine,setLine);
rect = Rectangle()
rect.line = 55 # 可以
rect.line = '44' # ValueError: wrong type.