派生类中扩展属性
对于在父类中存在的属性,如果要在其派生类中继续扩展属性
可以这样实现
1 class Valley: 2 def __init__(self): 3 self._name = None 4 5 @property 6 def name(self): 7 return self._name 8 9 @name.setter 10 def name(self, val): 11 try: 12 assert val.startswith("g") 13 except AssertionError: 14 self._name = "g" + val 15 else: 16 self._name = val 17 18 19 class SubValley(Valley): 20 @Valley.name.setter 21 def name(self, val): 22 if len(val) >= 3: 23 print(">>长度检查通过") 24 else: 25 raise Exception("{}长度应大于等于3".format(val)) 26 super(SubValley, SubValley).name.__set__(self, val) 27 28 29 if __name__ == '__main__': 30 obj = SubValley() 31 obj.name = 'lee' 32 print(obj._name)
output:
>>长度检查通过
glee