i*****f 发帖数: 578 | 1 class Planet:
@property
def diameter(self):
# a getter
return self.__diameter
@diameter.setter
def diameter(self, diameter):
# a setter
if diameter<0:
raise ValueError("impossible")
self.__diameter = diameter
def __init__(self, diameter):
self.diameter = diameter
mars = Planet(100)
print mars.diameter
mars.diameter = -10 # ValueError |
i*****f 发帖数: 578 | 2 Looks somewhat weired compared to other language setter/getter
【在 i*****f 的大作中提到】 : class Planet: : @property : def diameter(self): : # a getter : return self.__diameter : @diameter.setter : def diameter(self, diameter): : # a setter : if diameter<0: : raise ValueError("impossible")
|
m*****g 发帖数: 54 | 3 a better version
class Planet:
def getter(self):
return self.__diameter
def setter(self, value):
self.__diameter = value
diameter = property(getter, setter)
instance = Planet()
print(Planet.diameter) # call getter
instance.diameter = 1000 # cal setter
【在 i*****f 的大作中提到】 : class Planet: : @property : def diameter(self): : # a getter : return self.__diameter : @diameter.setter : def diameter(self, diameter): : # a setter : if diameter<0: : raise ValueError("impossible")
|
i*****f 发帖数: 578 | 4 谢谢补充!
【在 m*****g 的大作中提到】 : a better version : class Planet: : def getter(self): : return self.__diameter : def setter(self, value): : self.__diameter = value : diameter = property(getter, setter) : instance = Planet() : print(Planet.diameter) # call getter : instance.diameter = 1000 # cal setter
|