类的创建与销毁
__new__
创建类对象实例,__init__
初始化类对象实例
1 | class A: |
2 | def __init__(self): |
3 | print(self) |
4 | print('init') |
5 | |
6 | A() |
7 | <__main__.A object at 0x10db1f3c8> |
8 | init |
9 | |
10 | class A: |
11 | def __new__(cls, *args, **kwargs): |
12 | print('new') |
13 | print(cls) |
14 | return object.__new__(cls) |
15 | |
16 | A() |
17 | new |
18 | <class '__main__.A'> #A类对象 |
19 | <__main__.A at 0x10ded4b00> #A类实例 |
20 |
|
21 | object.__new__(A) |
22 | <__main__.A at 0x10d945320> |
23 |
|
24 | object.__new__用于创建对象 |
25 |
|
26 | class A: |
27 | def __new__(cls, *args, **kwargs): |
28 | print('new') |
29 | return object.__new__(cls) |
30 | |
31 | def __init__(self): |
32 | print('init') |
33 | self.x = 3 |
34 | |
35 | def __del__(self): |
36 | print('del') |
37 | |
38 | A() |
39 | new |
40 | init |
41 | <__main__.A at 0x10db82b00> |
42 | |
43 | a=A() |
44 | new |
45 | init |
46 | |
47 | del a |
48 | del |
元编程
1 | from collections import nametuple |
2 | |
3 | Person = nametuple('Person', ['name', 'age']) # 神奇之处在于用代码创建了一种新的类型,也就是代码具有写代码的能力 |
这种能力叫做元编程,通过元编程,我们可以控制类创建的过程
类创建的过程:
- 成员
- 继承列表
1 | class DisplayMixin: |
2 | def display(self): |
3 | print(self) |
4 | |
5 | class A(DisplayMixin): |
6 | pass |
7 | |
8 | A().display() |
9 | <__main__.A object at 0x10db8a7b8> |
10 | |
11 | debug = True |
12 | |
13 | if debug: |
14 | B = type('B', (DisplayMixin, object), {}) |
15 | else: |
16 | B = type('B', (), {}) |
17 | |
18 | B().display() |
19 | <__main__.B object at 0x10d2c2828> |
20 | |
21 | |
22 | class Meta(type): |
23 | def __new__(cls, name, bases, clsdict): |
24 | new_bases = [DisplayMixin] |
25 | new_bases.extend(bases) |
26 | return super().__new__(cls, name, tuple(new_bases), clsdict) |
27 | |
28 | def __init__(self, name, bases, clsdict): |
29 | super().__init__(name, bases, clsdict) |
30 | |
31 | class C(metaclass= Meta): |
32 | pass |
33 | |
34 | C().display() |
35 | <__main__.C object at 0x10d406ba8> |