__init__、__new__方法详解

2022-10-16,,,

__init__详解

class dog(object):
    def __init__(self):
        print('init方法')

    def __del__(self):
        print('del方法')

    def __str__(self):
        print('str方法')

    def __new__(cls, *args, **kwargs):
        print('new方法')
        return object.__new__(cls)

xtq=dog()

'''
相当于要做三件事:
1、调用__new__方法来创建对象,然后找一个变量来接收__new__的返回值,这个返回值表示创建出来的对象的引用
2、__init__(刚创建出来的引用)
3、返回对象的引用
在 c++、java中的构造方法用来创建、初始化
在python中实际由 __new__、__init__ 来创建、初始化,所以init不等价于构造方法
'''

 

init方法为对象定制自己独有的特征



#方式一、为对象初始化自己独有的特征
class people:
    country='china'
    x=1
    def run(self):
        print('----->', self)

# 实例化出三个空对象
obj1=people()
obj2=people()
obj3=people()

# 为对象定制自己独有的特征
obj1.name='egon'
obj1.age=18
obj1.sex='male'

obj2.name='lxx'
obj2.age=38
obj2.sex='female'

obj3.name='alex'
obj3.age=38
obj3.sex='female'

# print(obj1.__dict__)
# print(obj2.__dict__)
# print(obj3.__dict__)
# print(people.__dict__)





#方式二、为对象初始化自己独有的特征
class people:
    country='china'
    x=1
    def run(self):
        print('----->', self)

# 实例化出三个空对象
obj1=people()
obj2=people()
obj3=people()

# 为对象定制自己独有的特征
def chu_shi_hua(obj, x, y, z): #obj=obj1,x='egon',y=18,z='male'
    obj.name = x
    obj.age = y
    obj.sex = z

chu_shi_hua(obj1,'egon',18,'male')
chu_shi_hua(obj2,'lxx',38,'female')
chu_shi_hua(obj3,'alex',38,'female')





#方式三、为对象初始化自己独有的特征
class people:
    country='china'
    x=1

    def chu_shi_hua(obj, x, y, z): #obj=obj1,x='egon',y=18,z='male'
        obj.name = x
        obj.age = y
        obj.sex = z

    def run(self):
        print('----->', self)


obj1=people()
# print(people.chu_shi_hua)
people.chu_shi_hua(obj1,'egon',18,'male')

obj2=people()
people.chu_shi_hua(obj2,'lxx',38,'female')

obj3=people()
people.chu_shi_hua(obj3,'alex',38,'female')




# 方式四、为对象初始化自己独有的特征
class people:
    country='china'
    x=1

    def __init__(obj, x, y, z): #obj=obj1,x='egon',y=18,z='male'
        obj.name = x
        obj.age = y
        obj.sex = z

    def run(self):
        print('----->', self)

obj1=people('egon',18,'male') #people.__init__(obj1,'egon',18,'male')
obj2=people('lxx',38,'female') #people.__init__(obj2,'lxx',38,'female')
obj3=people('alex',38,'female') #people.__init__(obj3,'alex',38,'female')


# __init__方法
# 强调:
#   1、该方法内可以有任意的python代码
#   2、一定不能有返回值
class people:
    country='china'
    x=1

    def __init__(obj, name, age, sex): #obj=obj1,x='egon',y=18,z='male'
        # if type(name) is not str:
        #     raise typeerror('名字必须是字符串类型')
        obj.name = name
        obj.age = age
        obj.sex = sex


    def run(self):
        print('----->', self)


# obj1=people('egon',18,'male')
obj1=people(3537,18,'male')

# print(obj1.run)
# obj1.run() #people.run(obj1)
# print(people.run)

《__init__、__new__方法详解.doc》

下载本文的Word格式文档,以方便收藏与打印。