构造对象的常用到几个概念:
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>
可以看到obj1
和obj2
是一个实例。
有趣的是,每次实例化Singleton
的时候返回的实例都是同一个,而且 obj1.instance
就是 obj1
的一个引用(即自己)。