1 class Animal(object): 2 name = "hello" 3 4 def __init__(self, name): 5 self.name = name 6 self.__num = 100 7 8 @classmethod # 类方法,只能访问类属性,不能调用实例属性 9 def talk(self): 10 print("%s talk wang" % self.name) 11 12 def walk(self): 13 print("%s walking now" % self.name) 14 15 @staticmethod # 静态方法,不能直接访问类属性,以及实例属性 16 def habbit(self): 17 print(" %s habbit ..." % self.name) 18 19 @property # 属性,将类方法变成类属性形式对外提供访问 20 def total(self): 21 print("total pro is %s" % self.__num) 22 23 @property 24 def total_num(self): 25 print("total num pro is %s" % self.__num) 26 27 @total_num.setter 28 def total_num(self, num): # 静态属性修改值,如果要修改,则必须传入一个参数 29 self.__num = num 30 print("total num set is %s" % self.__num) 31 32 @total_num.deleter 33 def total_num(self): 34 print("total num del is %s" % self.__num) 35 del self.__num 36 37 newdog = Animal("san") 38 newdog.talk() 39 newdog.walk() 40 newdog.habbit(newdog) 41 print(newdog._Animal__num) 42 newdog.total 43 newdog.total_num 44 newdog.total_num = 3 45 del newdog.total_num 46 newdog.total_num # 已经删除了该实例属性,所以不存在了,报错
原文:http://www.cnblogs.com/zengchunyun/p/5242175.html