Python - 类(class)的变量 和 对象(object)的变量 详解 及 代码
2014-03-03 09:12
721 查看
类(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.
本文出自 “永不言弃” 博客,请务必保留此出处http://spikeking.blog.51cto.com/5252771/1387935
相关文章推荐
- Python - 类(class)的变量 和 对象(object)的变量 详解 及 代码
- Python - 类(class)的构造器(__init__) 详解 及 代码
- Python - 类(class)的构造器(__init__) 详解 及 代码
- 看python官方说明学python-class-object-类、对象-之区域和名空间
- c# 把一个匿名对象赋值给一个Object类型的变量后,怎么取这个变量? c# dynamic动态类型和匿名类 详解C# 匿名对象(匿名类型)、var、动态类型 dynamic 深入浅析C#中的var和dynamic
- Python面向对象的基础知识:类Class,对象(Object),实例(Instance)
- Python:类与对象的变量[SimpleClass.py]
- python中的常量和变量代码详解
- Python探险--变量与可变对象
- Python对象(变量)
- python 环境变量和import模块导入方法(详解)
- python中requests库session对象的妙用详解
- Python元组及文件核心对象类型详解
- python函数参数是值传递还是引用传递(以及变量间复制后是否保持一致):取决于对象内容可变不可变
- class,类的详解, python, 笨方法学python
- python入门:python的变量类型详解
- scala-29:Case class和Case object代码实战解析
- Python 类与对象变量
- Python 错误和异常代码详解
- Python 3.7新功能之dataclass装饰器详解