Python 类高级用法梳理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/8/20 8:44
# @Author : Ropon
# @File : test6.py

# class Foo(object):
# # def __iter__(self):
# # return iter([12, 34, 56])
#
# def __iter__(self):
# yield 11
# yield 22
# yield 33
#
#
# obj = Foo()
#
# for item in obj:
# print(item)

# 对象可循环,要变成可迭代对象,有__iter__(self) 方法

# class Foo(object):
# def __new__(cls, *args, **kwargs):
# return super(Foo, cls).__new__(cls)
# # return object.__new__(cls)
# # return 12345
#
# obj = Foo()
# print(obj)

# __new__ 返回值决定对象是什么

# 对象由类创建,类有type创建,可通过metaclass 指定由谁创建类

# 方式一
# class Foo(object):
# aa = 12
#
# def func1(self):
# return 88

# 方式二
# Foo = type('Foo', (object, ), {'aa': 12, 'func1': lambda self: 88})
#
# obj = Foo()
# print(obj.func1())
# print(Foo.aa)

# class MyType(type):
# def __init__(self, *args, **kwargs):
# print('创建类')
# super(MyType, self).__init__(*args, **kwargs)
#
# def __call__(cls, *args, **kwargs):
# print('类实例化,通过__call__触发类的__new__ 和 __init__ 方法')
# obj = cls.__new__(cls, *args, **kwargs)
# cls.__init__(obj, *args, **kwargs)
# return obj
#
# class Foo(object, metaclass=MyType):
# ab = 333
#
# def __init__(self):
# pass
#
# def __new__(cls, *args, **kwargs):
# return super(Foo, cls).__new__(cls)
#
# def func1(self):
# return 888
#
# obj = Foo()
# print(obj.func1())

# 创建类时,先执行metaclass 指定的__init__ 方法
# 类实例化时,先执行metaclass 指定的__call__ 方法 触发类的__new__ 和 __init__ 方法

class Foo(object):
cc = 66

def __init__(self, errcode=0, errmsg='ok'):
self.errcode = errcode
self.errmsg = errmsg

def func1(self):
return 888

# print(dir(Foo))
lst = dir(Foo)
nlst = []
for item in lst:
if not item.startswith('_'):
nlst.append(item)
print(nlst)
obj = Foo()
print(obj.__dict__)

# dir 查看类的成员
# __dict__ 查看对象内部存储的所有属性名和属性值组成的字典