程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python magic method (1):__ new __ (cls[, *args]) method

編輯:Python

Python There are some magical ways to do it , They are always surrounded by double underscores , They're object-oriented Python Everything . They are special ways to add magic to your classes , If your object implements ( heavy load ) A magic method , Then this method will be automatically used in special cases Python The call .

Basic magic methods ——__new __

function

Create an object ( from object Provide , Generally, there is no need to rewrite ), Is the first method called when an object is instantiated .Python Medium  __new__()  Methods are new methods in new classes ,Python Construction method in  __init__()  Responsible for instantiating the class , And in the  __init__()  Perform before ,__new__()  Responsible for making such an instance object , In order to  __init__()  To enrich the instance object ( Add attributes, etc ).

Parameters

The first parameter cls Represents the class containing the method , It is an automatic parameter transfer ; Parameters more Is an indefinite length parameter , not essential .

Return value

An object ( Generally, it is the instance object of this class ).

Application scenarios

Mainly used to inherit an immutable type , such as str etc.

Examples of use

class MyText(str):
def __new__(cls, string):
# This method can change the object before instantiation
string = string.upper()
# Returns the object
return super().__new__(cls, string)
# return string
# This kind of return sample And string data , meanwhile __init__ It's not going to be implemented
def __init__(self, str1):
self.str1 = str1
sample = MyText("this is a example")
print(sample)

Execution results :

THIS IS A EXAMPLE
class Person(object):
def __new__(cls, *args, **kwargs):
print("call __new__()")
instance = super().__new__(cls)
return instance
def __init__(self):
print("call __init__()")
p = Person()

Execution results :

call __new__()
call __init__()
class Person1(object):
def __new__(cls, *args, **kwargs):
print("call Person __new__()")
instance = super().__new__(cls)
return instance
class Student(object):
def __new__(cls, *args, **kwargs):
print("call Student __new__()")
instance = object.__new__(Person1, *args, **kwargs)
return instance
stu = Student()
print("Type stu =", type(stu))

Execution results :

call Student __new__()
Type stu = <class '__main__.Person1'>

summary

Python Medium  __new__()  Method is a static method responsible for creating class instances , And this method will be used in init() Called before initializing the method . In general , We're overwriting  __new__()  Before the implementation of , Will be used first super Calling the new Method .

Python Medium  __new__()  Methods are new methods in new classes ,Python Construction method in  __init__()  Responsible for instantiating the class , And in the  __init__()  Perform before ,__new__()  Responsible for making such an instance object , In order to  __init__()  To enrich the instance object ( Add attributes, etc ).

meanwhile ,__new__()  Method also determines whether to use the  __init__()  Method , because  __new__()  You can call the constructor of another class or directly return another object as an instance of this class .

When instantiating an object , First call __new__ Method to allocate storage space for an object , And return the reference of the object . After the interpreter gets the reference of the object , It will be passed as the first parameter to __init__ Method . If no instance object of this class is returned , be __init__ Method will not be called .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved