__new__() __init__方法

__new__方法是用来生成实例的

__new__主要用来定制化不可变类对象,

 

#__new__的使用
class Test:
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance=super(Test, cls).__new__(cls)
        return cls.instance

t1 = Test()
t2 = Test()
print(id(t1))
print(id(t2))


class Test2:
    #这里的a,b是用来接收生成实例的变量,参数的命名随意
    def __new__(cls, a, b):
        #return super(Test2, cls).__new__(cls, a, b) #貌似在python2里面要对这两个数据传入 报这种错误object() takes no parameters
        return super(Test2, cls).__new__(cls)

    def __init__(self, name, age):
        self.name = name
        self.age = age


t3 = Test2('jiangqijun', 18)
print(t3.name) #jiangqijun

'''
__new__和__init__调用的步骤
t3 = Test2('jiangqijun', 18)
1、首先调用的是__new__生成一个实例
2、再调用__init__初始化实例里面的变量
'''

'''
__new__的用法一:
用于生成不可变数据结构的类
假如我们需要一个永远都是正数的整数类型,通过集成int,我们可能会写出这样的代码。
使用__init__是无法实现的
要使用下面的__new__方法
'''


class Test3(int):
    def __init__(self, value):
        self.value = abs(value)
        self.age = 1+1


t4 = Test3(-4)
print(t4) #这里还是-4


class Test4(int):
    def __new__(cls, value):
        return super(Test4, cls).__new__(cls, abs(value))


t5 = Test4(-9)
print(t5)


'''
__new__的用法二:
用于生成单例模式
'''


class Singleton(object):
    def __new__(cls):
        # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)
        return cls.instance


obj1 = Singleton()
obj2 = Singleton()

obj1.attr1 = 'value1'
print(obj1.attr1, obj2.attr1)
print(obj1 is obj2)

http://python.jobbole.com/86506/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值