构造函数和析构函数如何工作? [英] How do constructors and destructors work?
问题描述
我正在尝试理解此代码:
I'm trying to understand this code:
class Person:
'''Represents a person '''
population = 0
def __init__(self,name):
//some statements and population += 1
def __del__(self):
//some statements and population -= 1
def sayHi(self):
'''grettings from 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 one here'
else:
print 'There are still %d guyz left ' % Person.population
rohan = Person('Rohan')
rohan.sayHi()
rohan.howMany()
sanju = Person('Sanjivi')
sanju.howMany()
del rohan # am i doing this correctly?
析构函数是如何被调用的-自动还是我必须在 main中添加一些东西
How does the destructor get invoked -- automatically or do I have to add something in the "main" program/class like above?
输出:
初始化人员数据
>
******************************************
初始化Rohan
************************************* *****
人口现在是:1
我叫Rohan
i是这里唯一的人
正在初始化的人数据
**********************************************
初始化Sanjivi
********************************** ********
现在的人口是:2
如果有人去世:
*********** **************************************
Sanjivi Bye Bye世界
在那里还剩1个人吗?
i是这里唯一的一个人
如果有人去世:
************** ********************************
Rohan Bye Bye world < br>
i是地球上最后一个人
现在的人口是:0
Initializing person data
******************************************
Initializing Rohan
******************************************
Population now is: 1
Hi My name is Rohan
i am the only one here
Initializing person data
******************************************
Initializing Sanjivi
******************************************
Population now is: 2
In case Person dies:
******************************************
Sanjivi Bye Bye world
there are still 1 people left
i am the only one here
In case Person dies:
******************************************
Rohan Bye Bye world
i am the last person on earth
Population now is: 0
如果需要,我也可以粘贴整个课程。我正在学习:
http://www.ibiblio.org/swaroopch / byteofpython / read /
If required I can paste the whole lesson as well. I'm learning from: http://www.ibiblio.org/swaroopch/byteofpython/read/
推荐答案
这里是一个有点自以为是的答案。
Here is a slightly opinionated answer.
不要使用 __ del __
。这不是C ++或为析构函数构建的语言。 __ del __
方法确实应该在Python 3.x中消失,尽管我确信有人会发现一个有意义的用例。如果您需要使用 __ del __
,请注意 http://docs.python.org/reference/datamodel.html :
Don't use __del__
. This is not C++ or a language built for destructors. The __del__
method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use __del __
, be aware of the basic limitations per http://docs.python.org/reference/datamodel.html:
-
__ del __
在垃圾收集器恰巧正在收集对象时调用,而不是在丢失对对象的最后一个引用时,而不是在执行del对象$时调用c $ c>。
-
__ del __
负责在其中调用任何__ del __
一个超类,尽管尚不清楚
是按方法解析顺序(MRO)还是只是调用每个超类。 - 具有
__ del __
意味着垃圾收集器放弃了检测和清除任何循环链接的操作,例如丢失对链接列表的最后一个引用。您可以从gc.garbage
获取被忽略对象的列表。您有时可以使用弱引用来完全避免循环。时不时对此进行辩论:请参见 http://mail.python .org / pipermail / python-ideas / 2009-October / 006194.html 。 -
__ del __
函数可能会作弊,保存对对象的引用并停止垃圾回收。 -
__ del __
中显式引发的异常将被忽略。 -
__ del __
对__ new __
的补充远远超过__ init __
。这变得令人困惑。参见 http://www.algorithm.co.il/blogs/index.php/programming/python/python-gotchas-1- del -is-not-the-opposite- - init / 进行解释和了解。 -
__ del __
不是 Python中深受喜爱的孩子。您会注意到sys.exit()文档没有指定是否在退出之前收集垃圾,并且存在很多奇怪的问题。在全局变量上调用__ del __
会引起奇怪的排序问题,例如 http: //bugs.python.org/issue5099 。即使__ init __
失败,也应该调用__ del __
吗?参见 http://mail.python.org/pipermail/ python-dev / 2000-March / thread.html#2423 来获取长线程。
__del__
is called when the garbage collector happens to be collecting the objects, not when you lose the last reference to an object and not when you executiondel object
.__del__
is responsible for calling any__del__
in a superclass, though it is not clear if this is in method resolution order (MRO) or just calling each superclass.- Having a
__del__
means that the garbage collector gives up on detecting and cleaning any cyclic links, such as losing the last reference to a linked list. You can get a list of the objects ignored fromgc.garbage
. You can sometimes use weak references to avoid the cycle altogether. This gets debated now and then: see http://mail.python.org/pipermail/python-ideas/2009-October/006194.html. - The
__del__
function can cheat, saving a reference to an object, and stopping the garbage collection. - Exceptions explicitly raised in
__del__
are ignored. __del__
complements__new__
far more than__init__
. This gets confusing. See http://www.algorithm.co.il/blogs/index.php/programming/python/python-gotchas-1-del-is-not-the-opposite-of-init/ for an explanation and gotchas.__del__
is not a "well-loved" child in Python. You will notice that sys.exit() documentation does not specify if garbage is collected before exiting, and there are lots of odd issues. Calling the__del__
on globals causes odd ordering issues, e.g., http://bugs.python.org/issue5099. Should__del__
called even if the__init__
fails? See http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423 for a long thread.
但是,另一方面:
-
__ del __
意味着您不会忘记调用关闭语句。参见 http://eli.thegreenplace.net/2009 / 06/12 / safe-using-destructors-in-python / 获取专业的__ del __
观点。这通常是关于释放ctype或其他特殊资源的。
__del__
means you do not forget to call a close statement. See http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/ for a pro__del__
viewpoint. This is usually about freeing ctypes or some other special resource.
我的个人理由是不喜欢 __ del__
函数。
And my pesonal reason for not liking the __del__
function.
- 每次有人提出
__ del __
时,分解成三十个混乱的消息。 - 它打破了Python Zen中的这些项目:
- 复杂度比
- 特殊情况还不足以打破规则。
- 错误绝不能默默传递。
- 面对歧义,拒绝诱惑。
- 应该有一种-最好只有一种-显而易见的方法。
- 如果难以解释该实现,则是个坏主意。
- Everytime someone brings up
__del__
it devolves into thirty messages of confusion. - It breaks these items in the Zen of Python:
- Complex is better than complicated.
- Special cases aren't special enough to break the rules.
- Errors should never pass silently.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one-- and preferably only one --obvious way to do it.
- If the implementation is hard to explain, it's a bad idea.
因此,找到不使用
__ del __
的原因。So, find a reason not to use
__del__
.这篇关于构造函数和析构函数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!