Python中一切皆是对象,每个对象都可以有多个属性。Python是如何管理这些属性呢?我们来探讨一下。
class bird(object): feather = True class chicken(bird): fly = False def __init__(self, age): self.age = age summer = chicken(2) print(bird.__dict__) print(chicken.__dict__) print(summer.__dict__)
class bird(object): feather = True class chicken(bird): fly = False def __init__(self, age): self.age = age def getAdult(self): if self.age > 1.0: return True else: return False adult = property(getAdult) # property is built-in summer = chicken(2) print(summer.adult) summer.age = 0.5 print(summer.adult)
class num(object): def __init__(self, value): self.value = value def getNeg(self): return -self.value def setNeg(self, value): self.value = -value def delNeg(self): print("value also deleted") del self.value neg = property(getNeg, setNeg, delNeg, "I'm negative") x = num(1.1) print(x.neg) x.neg = -22 print(x.value) print(num.neg.__doc__) del x.neg
class bird(object): feather = True class chicken(bird): fly = False def __init__(self, age): self.age = age def __getattr__(self, name): if name == 'adult': if self.age > 1.0: return True else: return False else: raise AttributeError(name) summer = chicken(2) print(summer.adult) summer.age = 0.5 print(summer.adult) print(summer.male)
__dict__分层存储属性。每一层的__dict__只存储该层新增的属性。子类不需要重复存储父类中的属性。
即时生成属性是值得了解的概念。在Python开发中,你有可能使用这种方法来更合理的管理对象的属性。
一入python深似海--对象的属性,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u010367506/article/details/33364855