【原创】 linux-python …

来源:互联网 发布:陕钢集团网络大学 编辑:程序博客网 时间:2024/05/21 03:26
linux-python __del__,__init__用例说明

原创所有,转载请附明本文超链接地址以及作者,谢谢!http://blog.sina.com.cn/s/blog_83dc494d0101c4dh.html
今天看一本书,《简明 Python 教程》,第11章 面向对象的编程--类与对象的方法,中提到了__del__方法,我看python学python以来真没遇到过del是这样的用法,而且也没有用这个方法,不过想想init之后就释然了,这或许是python独有的处理机制吧。init相当于C#中的构造函数,可以理解为初始化吧,不过初始化变量一般指赋值~这样好记点,都是对象嘛。

首先分析如下代码:
一个Person的类,有一个变量:population,四个方法:sayHi,howMany,__init__,__del__。
-------------------------------------------------------------------------------------------------
#!/usr/bin/env python
# Filename: objvar.py

class Person:
'''Represents a person.'''
population=0

def __init__(self,name):
'''Initializes the person's data.'''
self.name=name
print '(Initializing %s)' %self.name
#When this person is created, he/she adds to thepopulation
Person.population+=1
def __del__(self):
'''I am dying.'''
print '%s says bye.' %self.name
Person.population-=1
if Person.population==0:
print 'I am the last one.'
else:
print 'There are still %d people left.'%Person.population
def sayHi(self):
'''Greeting by the person.'''
print 'Hi, my name is %s.' %self.name
def howMany(self):
'''Prints the current population.'''
if Person.population==1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' %Person.population

swaroop=Person('Swaroop')
swaroop.sayHi()
tim = Person('Tim')
tim.howMany()
print '-'*10,swaroop.population,'-'*10
-------------------------------------------------------------------------------------------------
zhangzhipeng@zhangzhipeng-K53SD:~$ pythonobjvar.py 
(Initializing Swaroop)
Hi, my name is Swaroop.
(Initializing Tim)
We have 2 persons here.
---------- 2 ----------
Tim says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.
--------------------------------------------------------------------------------------------------
可以看到,当new一个类的时候,首先会把参数传到init函数中,因为打印出init函数体中的内容了。
接着看,print '-'*10,swaroop.population,'-'*10是我在类中定义的最后一个函数就是打印一点东西,以便区分用户定义方法完毕。但是可以看到,后面还会打印东西,正是__del__函数中的内容~~.
init del 都是系统类特有的函数,我们在这里只是重构,让原有del函数体可能是 del self.name,清空这个元素之类的。但是我们这里让打印一些没有意义的祖父穿而已。

结束语:理解不是很深刻,请批评建议~

原创所有,转载请附明本文超链接地址以及作者,谢谢!http://blog.sina.com.cn/s/blog_83dc494d0101c4dh.html
0 0
原创粉丝点击