python init new 方法都是其构造方法。
__init__方法: init方法通常用在初始化一个类实例的时候.init其实不是实例化一个类的时候第一个被调用的方法。通常来实例化一个类时,最先被调用的方法,其实是new方法。
__new__: new方法接受的参数也是和init一样,但init是在类实例创建之后调用,而new方法也是创建这个类实例的方法
- init通常用于初始化一个新实例,控制这个初始化的过程,比如添加一些属性,做一些额外的操作,发生在类实例被创建完成之后。它是实例级别的方法
- new通常用于控制生成一个新实例的过程,他是类级别的方法。
class Animal(object):
def __init__(self, name, color):
print('__init__ called')
self.name = name
self.color = color
def __new__(cls, *args, **kwargs):
print('__new__ called')
print(args)
print(kwargs)
return super(Animal, cls).__new__(cls)
def __str__(self):
return '<Animal %s %s>' % (self.name, self.color)
if __name__ == '__main__':
dog = Animal('Dog', 'red')
print(dog)
输出结果如下:
__new__ called
('Dog', 'red')
{}
__init__ called
<Animal Dog red>
new方法主要是当你继承一些不可变的class时,如int,str,tuple,提供给你一个自定义这些类的实例化过程的途径,还有就是实现自定义的metaclass。
还可以用new实现设计模式中的单例模式
class SingleModle(object):
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super(SingleModle, cls).__new__(cls)
return cls.instance
if __name__ == '__main__':
obj1 = SingleModle()
obj2 = SingleModle()
obj1.params = 'hello world'
print(obj1.params)
print(obj2.params)
print(obj1 is obj2)
输出结果是
hello world
hello world
True
Metaclass 元类
- 旧版本的class是来源一个built-in type叫做instance. 如果实例化一个class后得到obj, 那么obj.class会显示它来源于哪个class, 但是type(obj)是instance. 下面的例子env是Python2.7
class Zoom: pass z = Zoom() print z.__class__ print type(z) #__main__.Zoom #<type 'instance'>
- 新版本的class联合了class和type的概念. 如果obj是一个新版本class的实例, 那么type(obj)和obj.class的返回结果是一样的. 在Python 3中, 所有class都是新版本的class. 有一句话, 那就是在Python中, everything is an object. Class本身也是object
# 熟悉的built-in class也是type for t in int, float, dict, list, tuple: print(type(t)) #<class 'type'> #<class 'type'> #<class 'type'> #<class 'type'> #<class 'type'> # type本身也是type print(type(type)) #<class 'type'>
- Zoom()创建了一个class Zoom的实例.
- Zoom的父class中的call()会被启动, 因为Zoom是新版本的class, 所以它的父class就是type, 所以type的class()方法会被调用.
- call()方法会调用new()以及init()方法.
- 如果Zoom没有定义这两个方法, 会使用Zoom的祖先中的这两个方法.
- 如果Zoom定义了这两个方法, 会覆盖祖先中的这两个方法
class Zoom:
pass
z = Zoom()
print(z.__class__)
print(type(z))
print(type(Zoom))
#<class '__main__.Zoom'>
#<class '__main__.Zoom'>
#<class 'type'>
1. z是Zoom的实例
2. Zoom是type的实例
3. type是type的实例
- type是一个metaclass, class是实例. 在Python 3中, 任何class都是type这个metaclass的实例
使用type定义class
- 使用type创建class. 英文上说叫dynamically创建class
- 用type创建class时有三个参数(, , )
- name指的就是class的名字, 它会变成class.name
- bases指的是这个class的祖先
- dct指的是class定义的一些method, attribute啥的
def f(self):
print('in f and attr =', self.attr)
# return self.attr
Zoom = type(
'Zoom',
(),
{
'attr': 100,
'attr_val': f
}
)
z=Zoom()
print(z.attr)
print(z.attr_val())
常规的定义方式
def fn(self, name = 'world'): #先定义一个函数
print('Hello, %s' % name)
Hello = type('Hello', (object, ), dict(hello=fn)) #创建Hello class,传入class的名称,继承的父类集合class的方法名与函数绑定,这里我们把fn绑定到hello上
h = Hello()
h.hello()
print(type(Hello))
print(type(h))
#Hello, world
#<class 'type'>
#<class '__main__.Hello'>
type作为元类(Metaclass)被继承
Myclass要继承自type, MyClass这个class本身的创建也需要type, type中的一些方法也会在创建class时用到, 不想把type的所有方法都实现, 只是想做一些基于它的自定义. 这里定义了new这个方法, 我们会打印所有的attrs, 这个方法所需要的三个参数其实跟刚刚type中的三个参数是一样的.
class MyClass(type):
def __new__(self, class_name, bases, attrs):
modified = {}
for name, value in attrs.items():
if name.startswith("__"):
modified[name] = value
else:
modified[name.upper()] = value
return type(class_name, bases, modified)
class SonClass(metaclass=MyClass):
color = "Red"
print(dir(SonClass))