提示信息

Python __new__

天使爱上吸血鬼 已关注

In Python, __new__ is a special method that is automatically called before the __init__ method when creating a new instance of a class. It is responsible for creating and returning a new instance of the class.

Here is an example to demonstrate the usage of __new__:

  1. class MyClass:
  2. def __new__(cls, *args, **kwargs):
  3. print("Creating a new instance")
  4. instance = super().__new__(cls) # Creating a new instance using the superclass __new__ method
  5. return instance
  6. def __init__(self, name):
  7. print("Initializing instance")
  8. self.name = name
  9. obj = MyClass("Example")

In this example, the __new__ method is defined in the MyClass class. It prints a message indicating that a new instance is being created and uses the super() function to call the __new__ method of the superclass. Finally, it returns the newly created instance.

After __new__ finishes, the __init__ method is called. It prints a message indicating that the instance is being initialized and sets the name attribute of the instance.

When running this example, you will see the following output:

  1. Creating a new instance
  2. Initializing instance

This shows that the __new__ method is called before the __init__ method and is responsible for creating the new instance.

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
天使爱上吸血鬼 关注 已关注

最近一次登录:2023-10-09 16:04:54   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图