如何在每次创建特定类的新对象时自动运行该类函数

2024-09-30 06:15:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道,每次在Python中创建一个类的新对象时,如何运行一个类函数/方法。假设每次我们创建一个特定类的新对象时,程序都会打印“Hello,youjustcreateanewobject”。提前谢谢

class question:
  def __init__(self):
    greeting(self)

  def greeting(self):
    print("Hello")

emg = question()

Tags: 对象方法函数self程序helloinitdef
1条回答
网友
1楼 · 发布于 2024-09-30 06:15:51

每次在init方法中创建新对象时,放入要执行的代码:

class MyClass():
    def __init__(self):
        print("Hello, you just created a new object!")
        self.DoMoreComplicatedStuff()

    def DoMoreComplicatedStuff(self):
        print("I am doing more complicated stuff!")      

a = MyClass()

相关问题 更多 >

    热门问题