在Python中的__new__用法详细介绍

2021年3月9日15:44:22 发表评论 1,008 次浏览

python

是一种面向对象的编程语言, 即Python中的所有对象都是对象。 Python中有一种特殊的方法, 称为

魔术方法

or

邓德方法

(此处的" dunder"表示"

双下划线

")。 Python中的Dunder或magic方法是方法名称中带有两个前缀和后缀下划线的方法。这些通常用于操作员重载。

魔术方法的几个示例是:

__在里面__

,

__加__

,

__len__

,

__repr__

等等

注意:进一步了解魔术方法点击这里.

__new__方法

每当实例化一个类

__新__

__在里面__

方法被调用。

__新__

创建对象时将调用方法, 并且

__在里面__

方法将被调用以初始化对象。在基层

Object

, __new__方法定义为静态方法, 需要传递参数

cls

.

cls

表示需要实例化的类, 并且编译器在实例化时自动提供此参数。

语法如下:

class class_name:
    def __new__(cls, *args, **kwargs):
        statements
        .
        .
        return super(class_name, cls).__new__(cls, *args, **kwargs)

注意:实例可以在里面创建__新__通过使用超功能或直接调用__新__对象的方法, 如果父类是对象的话。那是实例= super(MyClass, cls).__ new __(cls, * args, ** kwargs)or实例=对象.__ new __(cls, * args, ** kwargs)

如果类中同时存在__init__方法和__new__方法, 则将首先执行__new__方法并决定是否使用__init__方法, 因为其他类的构造函数可以由__new__方法调用, 或者可以简单地返回其他对象作为的实例。这个班。

例子:

# Python program to 
# demonstrate __new__
  
# don't forget the object specified as base
class A( object ):
     def __new__( cls ):
          print ( "Creating instance" )
          return super (A, cls ).__new__( cls )
  
     def __init__( self ):
         print ( "Init is called" )
  
A()

输出如下:

Creating instance
Init is called

上面的示例显示, 调用类名时会自动调用__new__方法, 而每次__new__方法返回该类的实例时, 都会调用__init__方法, 并将返回的实例作为__init__传递给__init__。自参数, 因此, 即使你要将该实例全局/静态保存在某个位置, 并且每次从__new__返回它, 那么每次执行此操作都会调用__init__。

这意味着, 如果__new__方法省略了super, 则__init__方法将不会执行。让我们看看是否是这种情况。

# Python program to
# demonstrate __new__
  
class A( object ):
     def __new__( cls ):
         print ( "Creating instance" )
  
     # It is not called
     def __init__( self ):
         print ( "Init is called" )
  
print (A())

输出如下:

Creating instance
None

在上面的示例中, 可以看出__在里面__方法未调用, 实例化被评估为None因为构造函数没有返回任何东西。让我们看看如果__new__和__init__方法都返回了什么会发生什么。

# Python program to
# demonstrate __new__
  
class A( object ):
     # new method returning a string
     def __new__( cls ):
         print ( "Creating instance" )
         return "lsbin"
  
class B( object ):
     # init method returning a string
     def __init__( self ):
         print ( "Initializing instance" )
         return "lsbin"
  
print (A())
print (B())

输出如下:

Creating instance
lsbin
Initializing instance
Traceback (most recent call last):
  File "/home/62216eb30d3856048eff916fb8d4c32d.py", line 17, in 
  
   
    print(B())
TypeError: __init__() should return None, not 'str'

调用__init__方法的处理程序会引发此TypeError, 从__init__方法返回任何内容都没有任何意义, 因为它的目的只是改变新创建实例的新鲜状态。

让我们尝试一个示例, 其中__new__方法返回另一个类的实例。

例子:

# Python program to
# demonstrate __new__ method
  
# class whose object
# is returned
class lsbin( object ):
     def __str__( self ):
         return "lsbin"
          
# class returning object
# of different class
class Geek( object ):
     def __new__( cls ):
         return lsbin()
          
     def __init__( self ):
         print ( "Inside init" )
          
print (Geek())

输出如下:

lsbin

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: