Python

您所在的位置:网站首页 python定义对象变量 Python

Python

2024-07-17 02:48:50| 来源: 网络整理| 查看: 265

类(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.



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭