Python - 类(class)的变量 和 对象(object)的变量 详解 及 代码

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




评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值