Python中的构造方法

时间:2025-03-22 00:03:39

在Java等语言中都有构造方法【进行对象的创建及初始化】这个东东,示例代码如下:

public class Student {
//成员变量
private String name;
private int age; //有参构造方法
public Student(String name,int age) {
this.name = name;
this.age = age;
} //成员方法
...
} // 创建对象
students = Student('张三', 18)

那么Python中有么,答案是肯定有的咯,在Python中是使用__new____init__来完成的。

__new__负责进行对象的创建,object中的__new__示例代码如下:

@staticmethod # known case of __new__
def __new__(cls, *more): # known special case of object.__new__
""" Create and return a new object. See help(type) for accurate signature. """
pass

__init__负责进行对象的初始化,object中的__init__示例代码如下:

def __init__(self): # known special case of object.__init__
""" Initialize self. See help(type(self)) for accurate signature. """
pass

示例代码:

class Test(object):
def __init__(self):
print("这是 init 方法") # 可以不写默认使用父类(object)中的的__new__
def __new__(cls): # 执行的优先级最高
print("这是 new 方法")
return object.__new__(cls) Test() 执行结果:
这是 new 方法
这是 init 方法

总结

  • __new__至少要有一个参数cls,代表要实例化的类,此参数在实例化时由Python解释器自动提供
  • __new__必须要有返回值,返回实例化出来的实例,这点在自己实现__new__时要特别注意,可以return父类__new__出来的实例,或者直接是object的__new__出来的实例
  • __init__有一个参数self,就是这个__new__返回的实例,__init____new__的基础上可以完成一些其它初始化的动作,__init__不需要返回值