python init new class

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/11 23:36
# @Author  : flyx
# @Site    : 
# @File    : newinit.py
# @Software: PyCharm
class Person(object):

    def __new__(cls,*args,**kwargs):
        print('__new__被调用执行了,cls的id为{0}'.format(id(cls)))
        obj = super().__new__(cls)
        print('创建的对象id为{0}'.format(id(obj)))
        return obj


    def __init__(self,name,age):
        print('__init__方法被调用了,self的id为'.format(id(self)))
        self.name = name
        self.age = age


print('object这个类对象的id{0}'.format(id(object)))
print('Person这个类对象的id{0}'.format(id(Person)))

# 创建Person类的实例对象
p1 = Person('张三',20)
print('p1的id{0}'.format(id(p1)))

object这个类对象的id140713382284992
Person这个类对象的id2351314789480
__new__被调用执行了,cls的id为2351314789480
创建的对象id为2351344788704
__init__方法被调用了,self的id为
p1的id2351344788704

猜你喜欢

转载自blog.csdn.net/qq_34608447/article/details/111087108