首先创建一个简单类:一个特性__radius 和 两个方法 setRadius() area()
然后,创建第二个类:把radius 和 area 变成属性。
/usr/bin/python3
#coding: utf-8
class Circle1:
def __init__(self, radius):
self.__radius = radius
def setRadius(self,newValue):
if newValue >= 0:
self.__radius = newValue
else: raise ValueError("Value must be positive")
def area(self):
return 3.14159 * (self.__radius ** 2)
class Circle2:
def __init__(self, radius):
self.__radius = radius
def __setRadius(self, newValue):
if newValue >= 0:
self.__radius = newValue
else: raise ValueError("Value must be positive")
radius = property(None, __setRadius) #属性设置方式一
@property #属性设置方式二
def area(self):
return 3.14159 * (self.__radius ** 2)
if __name__ == '__main__':
c1 = Circle1(10)
c1.setRadius(1)
print('c1:',c1.area())
c2 = Circle2(10)
c2.radius = 1
print('c2',c2.area)