《流畅的Python》12-构造对象

构造对象的常用到几个概念:
super(),__new__,__init__

__new____init__

一般将__init__称为构造方法,实际上
__new__用于实例化类,__init__用于初始化实例。
Python构造对象的伪代码:

def object_maker(the_class,some_arg):
    new_object=the_class.__new__(some_arg)
    if isininstance(new_object,the_class):
        the_class.__init__(new_class,some_arg) # 调用父类的方法,作用在自己身上。
    return new_object

下面两个语句基本等效:

x=Foo('bar')
x=object_maker(Foo,'bar')

super()

in python 3.7 docs:
super([type[, object-or-type]]) a build-in Function

super的讨论可见10年前的帖子stackoverflow
what-does-super-do-in-python

What’s the difference between:

class Child(SomeBaseClass):
    def __init__(self):
        super(Child, self).__init__()

and:

class Child(SomeBaseClass):
    def __init__(self):
        SomeBaseClass.__init__(self)

super()方便了代码的编写,而不需要指明父类,在 Python3 里,可以直接使用 super()

class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)

__new__用于单例模式

单例模式singleton,也叫单子模式,是一种常用的软件设计模式。 在应用这个模式时,单例对象的类必须保证只有一个实例存在。 许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。

class Singleton(object):
    def __new__(cls):
        # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)# 调用父类的__new__构造一个对象,并返回
        return cls.instance
 
obj1 = Singleton()
obj2 = Singleton()
 
obj1.attr1 = 'value1'
print(obj1)
print(obj1.instance)
print(obj1)
print(obj2)

<__main__.Singleton object at 0x7f501254fb38>
可以看到obj1obj2是一个实例。
有趣的是,每次实例化Singleton的时候返回的实例都是同一个,而且 obj1.instance 就是 obj1 的一个引用(即自己)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值