gpt4 book ai didi

python - 为什么一个对象在没有类的情况下仍然可以正常工作

转载 作者:太空狗 更新时间:2023-10-29 21:26:48 25 4
gpt4 key购买 nike

我是 Python 的新手。在阅读了 Python Tutorial Release 2.7.5 的一些章节后,我对 Python 作用域和 namespace 感到困惑。这个问题可能会重复,因为我不知道要搜索什么。

我创建了一个类和一个实例。然后我使用 del 删除了这个类。但是该实例仍然可以正常工作。为什么?

>>>class MyClass:    # define a class
... def greet(self):
... print 'hello'
...
>>>instan = MyClass() # create an instantiation
>>>instan
<__main__.MyClass instance at 0x00BBCDC8>
>>>instan.greet()
hello
>>>dir()
['instan', 'MyClass', '__builtins__', '__doc__', '__name__', '__package__']
>>>
>>>
>>>del MyClass
>>>dir()
['instan', '__builtins__', '__doc__', '__name__', '__package__']
>>>instan
<__main__.MyClass instance at 0x00BBCDC8> # Myclass doesn't exist!
>>>instan.greet()
hello

我对 OOP 知之甚少,所以这个问题看起来很简单。提前致谢。

最佳答案

Python 是一个 garbage collected语。当您执行 del MyClass 时,实际上并没有删除“类对象”(类也是对象),而只是从当前命名空间中删除了“名称”MyClass ,这是对类对象的某种引用。任何对象只要被某物引用就会保持事件状态。由于实例引用它们自己的类,因此只要至少有一个实例处于事件状态,该类就会保持事件状态。

当您重新定义一个类时(例如在命令行上),需要注意的一件事是:

In [1]: class C(object):
...: def hello(self):
...: print 'I am an instance of the old class'
In [2]: c = C()
In [3]: c.hello()
I am an instance of the old class
In [4]: class C(object): # define new class and point C to it
...: def hello(self):
...: print 'I am an instance of the new class'
In [5]: c.hello() # the old object does not magically become a new one
I am an instance of the old class
In [6]: c = C() # point c to new object, old class and object are now garbage
In [7]: c.hello()
I am an instance of the new class

旧类的任何现有实例都将继续具有旧行为,考虑到我提到的事情,这是有道理的。命名空间和对象之间的关系对于 python 来说有点特殊,但是一旦掌握它就不那么难了。给出了很好的解释here .

关于python - 为什么一个对象在没有类的情况下仍然可以正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18869342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com