类(class)的变量 和 对象(object)的变量 详解 及 代码
本文地址: http://blog.csdn.net/caroline_wendy/article/details/20356531
Python中, 类(class)的变量是所有对象共享使用, 只有一个拷贝, 所有对象修改, 都可以被其他对象所见;
对象(object)的变量由类的每个对象所拥有, 每个对象都包含自己的一份拷贝, 不会影响其他对象;
使用类的变量, ClassName.val; 而使用对象的变量,self.val;
类的方法, 是类使用的, 可以定义为静态(static)方法, 有两种方式:
#@staticmethod 或 method = staticmethod(method) ;
析构函数, __del__(双下划线), 在程序结束会自动调用, 也可以手动调用, del obj, 即可.
代码如下:
# -*- coding: utf-8 -*- #==================== #File: ClassExercise.py #Author: Wendy #Date: 2014-03-03 #==================== #eclipse pydev, python2.7 class GirlFriend: population = 0 def __init__(self, name): self.name = name print(‘(Initialize {0})‘.format(self.name)) GirlFriend.population += 1 def __del__(self): #析构器 print(‘{0} is being destroyed!‘.format(self.name)) GirlFriend.population -= 1 if GirlFriend.population == 0: print(‘{0} was the last one.‘.format(self.name)) else: #{0:d} 表示使用10进制输出 print(‘There are still {0:d} girl friends.‘.format(GirlFriend.population)) def sayLove(self): print(‘Greetings, my boy friend loves me, {0}.‘.format(self.name)) #@staticmethod def howMany(): print(‘We have {0:d} girl friends.‘.format(GirlFriend.population)) howMany = staticmethod(howMany) gf1 = GirlFriend(‘Caroline‘) gf1.sayLove() GirlFriend.howMany() gf2 = GirlFriend(‘Wendy‘) gf2.sayLove() GirlFriend.howMany() del gf1 #手动调用 程序结束会自动调用析构函数 del gf2 GirlFriend.howMany()
输出:
(Initialize Caroline) Greetings, my boy friend loves me, Caroline. We have 1 girl friends. (Initialize Wendy) Greetings, my boy friend loves me, Wendy. We have 2 girl friends. Caroline is being destroyed! There are still 1 girl friends. Wendy is being destroyed! Wendy was the last one. We have 0 girl friends.