首页 > 解决方案 > Python 类在 Google Colaboratory 上表现异常

问题描述

我在 Google Colab 上创建了 Python 类 Student。然而,出于某种奇怪的原因,在初始化对象 Jane 之前调用了析构函数,这令人费解。

我在下面附上了 Google Colab 的输出。

当我在 1) JupyterLab 和 2) 我的本地机器上测试相同的代码时,我得到了我期望的输出(附在下面)。

有人能告诉我为什么类在 Google Colab 中表现得很奇怪吗?

class Student:
  name = ''
  section = ''
  age = 0
  def __init__(self, name, section, age):
    self.name = name
    self.section = section
    self.age = age
  def __del__(self):
    print(f"{self.name} is graduating!")
  def print_details(self):
    print(f"Hi, my name is: {self.name} and I am in section {self.section}. My age is {self.age}")


ramu = Student('Ramu',3, 15)
ramu.print_details()
del(ramu)
jane = Student('Jane',1,14)
jane.print_details()

谷歌 Colab 输出

Hi, my name is: Ramu and I am in section 3. My age is 15
Ramu is graduating!
Jane is graduating!
Hi, my name is: Jane and I am in section 1. My age is 14

JupyterLab 和本地机器输出

Hi, my name is: Ramu and I am in section 3. My age is 15
Ramu is graduating!
Hi, my name is: Jane and I am in section 1. My age is 14

标签: pythonclassgoogle-colaboratory

解决方案


推荐阅读