Advance Python
Advance Python
0.0.1
2019 12 18
Contents
1 3
1.1 1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Python 5
2.1 2.1 python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 2.2 type object class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 2.3 python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.4 2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3 11
3.1 3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.2 3.2 python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.3 3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.4 3.4 len . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.5 3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4 15
4.1 4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
4.2 4.2 (abc ). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.3 4.3 isinstance type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.4 4.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.5 4.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.6 4.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.7 4.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.8 4.8 python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.9 4.9 super . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
5 27
i
5.1 5.1 python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.2 5.2 abc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.3 5.3 + += extend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.4 5.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
5.5 5.5 bisect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.6 5.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.7 5.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.8 5.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
7 39
7.1 7.1 python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
7.2 7.2 is == . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
7.3 7.3 del . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
7.4 7.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
7.5 7.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
8 43
8.1 8.1 property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
8.2 8.2 __getattr__ __getattribute__ . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.3 8.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
8.4 8.4 __new__ __init__ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
8.5 8.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
8.6 8.6 ORM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
8.7 8.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
9 55
9.1 9.1 python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
9.2 9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
9.3 9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
9.4 9.4 python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
9.5 9.5 UserList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
9.6 9.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
9.7 9.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
10 65
ii
11 Roadmap 67
iii
iv
AdvancePython, 0.0.1
Contents
Contents 1
AdvancePython, 0.0.1
2 Contents
CHAPTER 1
Introduce
1.1 1.1
1.1.1
• asyncio tornado
• python
• python
1.1.2
3
AdvancePython, 0.0.1
1.1.3
• python
• python
4 Chapter 1.
CHAPTER 2
Python
Introduce
2.1.1 python
• python
• python
def bar(name):
print('Hello %s' % name)
class Person(object):
def __init__(self, name):
( )
5
AdvancePython, 0.0.1
( )
def decorator_func():
print('from decorator_func')
return bar
def print_type(obj):
print(type(obj))
#
func = bar
func('Linda')
my_class = Person
my_class('Tom')
#
obj_list = []
obj_list.append(bar)
obj_list.append(Person)
for item in obj_list:
#
print_type(item)
#
deco_bar = decorator_func()
deco_bar('deco_bar')
2.1.2
handle
6 Chapter 2. Python
AdvancePython, 0.0.1
( )
2.2.1 type
• str linda
• type str
• type object
• type type ( C )
2.2.2 object
>>> int.__bases__
(<class 'object'>, )
>>> type.__bases__
(<class 'object'>, )
>>> object.__bases__
()
• str object
• type object
• object.__bases__ ()
• list dict
• object type
• type object
2.3.1
8 Chapter 2. Python
AdvancePython, 0.0.1
2.3.2 python
• None( )
• dict
• set frozenset
• with
set [Link]()
2.3.3
2.4 2.4
• python
• python
• python
2.4. 2.4 9
AdvancePython, 0.0.1
10 Chapter 2. Python
CHAPTER 3
Introduce
3.1 3.1
python
• python
class Company:
def __init__(self, employee_list):
[Link] = employee_list
11
AdvancePython, 0.0.1
( )
print(item)
3.2.1 python
• python company[:2]
• len(company)
3.3 3.3
3.3.1
• __repr__
• __str__
class Company:
def __init__(self, name):
[Link] = name
def __str__(self):
return '<Company [%s]>' % [Link]
def __repr__(self):
return '<Company [%s]>' % [Link]
company = Company('Apple')
print(company)
( )
12 Chapter 3.
AdvancePython, 0.0.1
( )
# Python
print(company.__repr__())
• __len__
• __getitem__
• __setitem__
• __delitem__
• __contains__
• __iter__
• __next__
• __call__
with
• __enter__
• __exit__
3.3.2
• __abs__
• __add__
class Num:
def __init__(self, num):
[Link] = num
def __abs__(self):
return abs([Link])
n = Num(-1)
print(abs(n))
( )
3.3. 3.3 13
AdvancePython, 0.0.1
( )
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'Vector(%s, %s)' % (self.x, self.y)
v1 = Vector(1, 3)
v2 = Vector(2, 4)
print(v1 + v2)
3.5 3.5
• python
• python
• len
14 Chapter 3.
CHAPTER 4
Introduce
4.1 4.1
4.1.1
class Cat:
def say(self):
print('I am a cat.')
class Dog:
def say(self):
print('I am a dog.')
class Duck:
def say(self):
print('I am a duck.')
# Python say
( )
15
AdvancePython, 0.0.1
( )
animal = Cat
animal().say()
#
animal_list = [Cat, Dog, Duck]
for an in animal_list:
an().say()
"""
class Animal:
def say(self):
print('I am a animal.')
# Animal say
class Cat(Animal):
def say(self):
print('I am a cat.')
# Java
Animal an = new Cat()
[Link]()
"""
tu = ('i5', 'i6')
s1 = set()
[Link]('i7')
[Link]('i8')
# list iterable
[Link](li2) # iterable
[Link](tu)
[Link](s1)
print(li1)
16 Chapter 4.
AdvancePython, 0.0.1
4.2.1
• python
#
class Company:
def __init__(self, name):
[Link] = name
def __len__(self):
return len([Link])
import abc
class CacheBase(metaclass=[Link]):
@[Link]
def get(self, key):
pass
@[Link]
def set(self, key, value):
pass
( )
( )
class MemoryCache(CacheBase):
pass
Mixin
• isinstance
• type
class A:
pass
class B(A):
pass
b = B()
print(isinstance(b, B))
print(isinstance(b, A))
# is id
print(type(b) is B)
print(type(b) is A) # False
4.4 4.4
class A:
aa = 1
18 Chapter 4.
AdvancePython, 0.0.1
( )
a = A(2, 3)
print(a.x, a.y, [Link])
[Link] = 111
[Link] = 100 # a aa 100 aa
print([Link], [Link])
4.5 4.5
4.5.1
• __init__
4.5.2 DFS
4.5. 4.5 19
AdvancePython, 0.0.1
• C D
20 Chapter 4.
AdvancePython, 0.0.1
4.5.3 BFS
4.5. 4.5 21
AdvancePython, 0.0.1
• B D B D D C
4.5.4 MRO C3
class D:
pass
class C(D):
pass
class B(D):
pass
print(A.__mro__)
# (<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>
,→, <class 'object'>) ( )
22 Chapter 4.
AdvancePython, 0.0.1
( )
B C D E
class D:
pass
class E:
pass
class C(E):
pass
class B(D):
pass
print(A.__mro__)
# (<class '__main__.A'>, <class '__main__.B'>, <class '__main__.D'>, <class '__main__.C'>
,→, <class '__main__.E'>, <class 'object'>)
4.6 4.6
• @staticmethod
• @classmethod
class Date:
def __init__(self, year, month, day):
[Link] = year
[Link] = month
[Link] = day
def tomorrow(self):
[Link] += 1
@staticmethod
( )
4.6. 4.6 23
AdvancePython, 0.0.1
( )
def date_from_str(date_str):
year, month, day = tuple(date_str.split('-'))
return Date(int(year), int(month), int(day))
@classmethod
def date_from_string(cls, date_str):
year, month, day = tuple(date_str.split('-'))
return cls(int(year), int(month), int(day))
def __str__(self):
return '{year}/{month}/{day}'.format(year=[Link], month=[Link], day=self.
,→day)
if __name__ == '__main__':
new_day = Date(2020, 2, 20)
new_day.tomorrow()
print(new_day)
date_str = '2020-12-12'
print(Date.date_from_str(date_str))
print(Date.date_from_string(date_str))
4.7 4.7
class User:
def __init__(self):
self.__age = 18
def get_age(self):
return self.__age
if __name__ == '__main__':
user = User()
print(user.get_age())
# print(user.__age)
( )
24 Chapter 4.
AdvancePython, 0.0.1
( )
# _class__attr,
print(user._User__age)
• python
• __dict__
• dir()
class User:
name = 'user'
class Student(User):
def __init__(self):
self.school_name = 'school'
if __name__ == '__main__':
stu = Student()
# __dict__ , C
print(stu.__dict__)
stu.__dict__['age'] = 18
print([Link])
print(User.__dict__)
print(dir(stu))
26 Chapter 4.
CHAPTER 5
Introduce
python
#
my_list = list()
my_list.append(100)
my_list.append(True)
#
import array
( )
27
AdvancePython, 0.0.1
( )
my_array = [Link]('i')
my_array.append(100)
#
my_array.append('abc')
python [Link]
python
• Iterable: __iter__
• Reversible: __reversed__
• Sized: __len__
• Container: __contains__
• +
• +=
• append extend
# +
l1 = [1, 2]
l2 = l1 + [3, 4]
print("type(l1): %d, and l1: %s" % (id(l1), l1))
print("type(l2): %d, and l2: %s" % (id(l2), l2))
# +=
l1 += ['3', '4']
( )
28 Chapter 5.
AdvancePython, 0.0.1
( )
l1 += ('5', '6')
l1 += range(2)
print("type(l1): %d, and l1: %s" % (id(l1), l1))
# +
# += __iadd__
5.4 5.4
5.4.1
'''
[start:end:step]
start 0
end ( )
step 1
start 0
end
step 1
step start end
'''
a_list[len(a_list):0] = [9] #
a_list[:0] = [1, 2] #
a_list[3:3] = [100] #
a_list[:2] = [100, 200] #
( )
5.4. 5.4 29
AdvancePython, 0.0.1
( )
a_list[3:] = [4, 5, 6] #
a_list[:3] = [] # 3
5.4.2
[Link] Sequence
import numbers
class Group:
def __init__(self, group_name, company_name, staff):
self.group_name = group_name
self.company_name = company_name
[Link] = staff
def __reversed__(self):
[Link]()
def __len__(self):
return len([Link])
def __iter__(self):
return iter([Link])
( )
30 Chapter 5.
AdvancePython, 0.0.1
( )
print('linda' in sub_group)
print(len(sub_group))
• bisect
import bisect
#
#
l1 = list()
[Link](l1, 10)
[Link](l1, 3)
[Link](l1, 2)
[Link](l1, 6)
5.6 5.6
• list python
• array
• deque
5.6.1 array
import array
list
my_array = [Link]('i')
my_array.append(100)
my_array.append('abc')
• list
5.7 5.7
5.7.1
# 1-20
odd_list = [i for i in range(21) if i % 2 == 1]
print(odd_list)
#
def handle_item(item):
return item * item
5.7.2
[] -> ()
32 Chapter 5.
AdvancePython, 0.0.1
5.7.3
5.7.4
5.8 5.8
• abc
• + += extend
• bisect
• list
5.8. 5.8 33
AdvancePython, 0.0.1
34 Chapter 5.
CHAPTER 6
Introduce
• Sized: __len__
• Iterable: __iter__
• Container: __contains__
• Mapping: Collection
• MutableMapping: Mapping
dict list
# dict Mapping
d = dict()
print(isinstance(d, Mapping))
35
AdvancePython, 0.0.1
PyCharm
d = {
'linda': {'company': 'Yahoo'},
'catherine': {'company': 'Google'}
}
#
# [Link]()
#
new_dict = [Link]()
#
import copy
new_dict_deep = [Link](d)
new_dict['linda']['company'] = 'Ali'
print(d)
print(new_dict)
print(new_dict_deep)
# key value,
print([Link]('key', 'value'))
[Link]({'name': 'linda'})
print(dd)
• c dict list
class MyDict(dict):
def __setitem__(self, key, value):
super().__setitem__(key, value * 2)
( )
( )
my_dict = MyDict(one=1)
print(my_dict) # 1, __setitem__
my_dict['one'] = 1
print(my_dict) # 2, __setitem__
• UserDict
• python c
• defaultdict __missing__
d2 = defaultdict(list)
# __missing__ UserDict __getitem__
value = d2['key']
print(value)
print(dict(d2))
# set
s1 = set('abcc')
print(s1) # {'a', 'c', 'b'}
6.6 6.6
Introduce
• java
• python
# a 1
a = 1
# a 'abc'
a = 'abc'
# :
la = [1, 2, 3]
lb = la
# is, id(a) id(b)
print(lb is la) # True, id
print(id(la), id(lb))
[Link](100)
print(lb) # lb la lb
39
AdvancePython, 0.0.1
7.2 7.2 is ==
• is id()
• ==
# intern
a1 = 1
a2 = 1
print(a1 is a2) # True
s1 = 'abc'
s2 = 'abc'
print(s1 is s2) # True
class People:
pass
# People
person = People()
print(type(person) is People) # True
# python
a = 1
b = a
del a
• del __del__
40 Chapter 7.
AdvancePython, 0.0.1
• 0
7.4 7.4
a, b
if __name__ == '__main__':
a, b = 1, 2
c = add(a, b)
print('a: %s, b: %s, c: %s' % (a, b, c))
# a: 1, b: 2, c: 3
# a
a, b
if __name__ == '__main__':
a, b = [1, 2], [3, 4]
c = add(a, b)
print('a: %s, b: %s, c: %s' % (a, b, c))
# a: [1, 2, 3, 4], b: [3, 4], c: [1, 2, 3, 4]
# a
a, b
if __name__ == '__main__':
a, b = (1, 2), (3, 4)
c = add(a, b)
print('a: %s, b: %s, c: %s' % (a, b, c))
( )
7.4. 7.4 41
AdvancePython, 0.0.1
( )
class Company:
def __init__(self, name, staff_list=[]):
[Link] = name
self.staff_list = staff_list
if __name__ == '__main__':
com1 = Company('com1', ['staff1', 'staff11'])
[Link]('staff111')
[Link]('staff11')
print(com1.staff_list)
com2 = Company('com2')
[Link]('staff2')
com3 = Company('com3')
[Link]('staff3')
• [] com2.staff_list com3.staff_list
7.5 7.5
• python
• is == =
• del
42 Chapter 7.
CHAPTER 8
Introduce
class User:
def __init__(self, name, birthday):
[Link] = name
[Link] = birthday
self._age = 0 # _
@property
def age(self):
return [Link]().year - [Link]
@[Link]
def age(self, value):
self._age = value
def get_age(self):
( )
43
AdvancePython, 0.0.1
( )
return self._age
if __name__ == '__main__':
user = User('linda', date(1987, 11, 14))
print([Link]) # @property
[Link] = 100 # @[Link]
print(user.get_age()) # self._age _age
• [Link]; self._age
• property
• [Link] = 100
8.2.1 __getattr__
class User:
def __init__(self, name):
[Link] = name
if __name__ == '__main__':
user = User('linda')
print([Link]) # Not found attribute age
• __getattr__,
• else
class User:
def __init__(self, info=None):
if not info:
info = {}
[Link] = info
44 Chapter 8.
AdvancePython, 0.0.1
( )
return [Link][item]
if __name__ == '__main__':
user = User({'name': 'linda', 'age': 18})
print([Link])
print([Link])
8.2.2 __getattribute__
class User:
def __init__(self, name):
[Link] = name
if __name__ == '__main__':
user = User('linda')
print([Link]) # get_attribute
print([Link]) # get_attribute
print([Link]) # get_attribute
• __getattribute__
8.3 8.3
property
• __get__ __set__
• __get__
8.3. 8.3 45
AdvancePython, 0.0.1
import numbers
class IntField:
def __init__(self):
self._data = None
class User:
age = IntField()
num = IntField()
if __name__ == '__main__':
user = User()
[Link] = 18
print(user.__dict__) # {} "age" __dict__
print([Link])
__getattribute__
( )
46 Chapter 8.
AdvancePython, 0.0.1
( )
class NonDataIntFiled:
def __get__(self, instance, owner):
print(instance)
print(owner)
return 100
class User:
age = NonDataIntFiled()
if __name__ == '__main__':
user = User()
# user.__dict__['age'] = 18
# [Link] = 18
# print(user.__dict__)
print([Link])
• __new__: self
__init__
• __init__:
• __new__ __init__
class User(object):
# user
def __new__(cls, *args, **kwargs):
# args = ('linda', )
# kwargs = {'age': 20}
# metaclass __new__
print('from __new__')
self = super().__new__(cls)
return self
if __name__ == '__main__':
user = User('linda', age=20)
PS:
• ->
• ->
8.5 8.5
• class
def create_class(name):
if name == 'user':
class User:
def __str__(self):
return 'User'
return User
48 Chapter 8.
AdvancePython, 0.0.1
( )
return 'Company'
return Company
MyClass = create_class('user')
obj = MyClass()
print(obj)
print(type(obj)) # <class '__main__.create_class.<locals>.User'>
• type
def func(self):
return 'I am from func.'
class Base:
def answer(self):
return 'I am from [Link].'
# type
User = type('User', (Base, ), {'name': 'user', 'func': func})
user = User()
print([Link])
print([Link]())
print([Link]())
print(type(user))
class MetaClass(type):
# User User __new__
def __new__(cls, name, bases, attrs, **kw):
return super().__new__(cls, name, bases, attrs, **kw)
def bar(self):
print('from bar.')
8.5. 8.5 49
AdvancePython, 0.0.1
#
class User:
name = CharFiled(db_column="", max_length=32)
age = IntFiled(db_column="", min_value=0, max_value=100)
class Meta:
db_table = 'user'
# ORM
user = User()
[Link] = 'linda'
[Link] = 18
[Link]()
ORM
class Field:
pass
class IntField(Field):
def __init__(self, db_column, min_value=0, max_value=100):
self.db_column = db_column
self.min_value = min_value
self.max_value = max_value
self._value = None
( )
50 Chapter 8.
AdvancePython, 0.0.1
( )
class CharField(Field):
def __init__(self, db_column, max_length=32):
self.db_column = db_column
self.max_length = max_length
self._value = None
#
class MetaClass(type):
def __new__(cls, name, bases, attrs, **kw):
# BaseModel Metaclass name age
if name == 'BaseModel':
return super().__new__(cls, name, bases, attrs, **kw)
fields = {}
for key, value in [Link]():
if isinstance(value, Field):
fields[key] = value
( )
( )
_meta['db_table'] = db_table
attrs['_meta'] = _meta
attrs['fields'] = fields
if [Link]('Meta'):
del attrs['Meta']
return super().__new__(cls, name, bases, attrs, **kw)
class BaseModel(metaclass=MetaClass):
def __init__(self, **kw):
for key, value in [Link]():
setattr(self, key, value)
super().__init__()
def save(self):
fields = OrderedDict([Link])
fields_str = ", ".join([value.db_column for value in [Link]()])
values_str = ', '.join([str(getattr(self, field)) if not isinstance(value,␣
,→ CharField)
else "'%s'" % str(getattr(self, field))
for field, value in [Link]()])
sql = "insert into %s (%s) values (%s)" % (self._meta['db_table'], fields_str,␣
,→ values_str)
print(sql)
# insert into user (name1, age) values ('linda', 20)
#
class User(BaseModel):
name = CharField('name1', max_length=16)
age = IntField('age', min_value=0, max_value=100)
( )
52 Chapter 8.
AdvancePython, 0.0.1
( )
class Meta:
db_table = 'user'
if __name__ == '__main__':
user = User(name='linda')
[Link] = 20
[Link]()
ORM
• (__set__, __get__)
• (MetaClass(type))
• ORM (BaseModel)
• objects
8.7 8.7
8.7. 8.7 53
AdvancePython, 0.0.1
54 Chapter 8.
CHAPTER 9
Introduce
• Iterable
• Iterator
9.2 9.2
__iter__ Iterator
55
AdvancePython, 0.0.1
class MyIterator(Iterator):
def __init__(self, employee):
[Link] = employee
[Link] = 0
def __next__(self):
#
#
#
try:
word = [Link][[Link]]
except IndexError:
raise StopIteration
[Link] += 1
return word
class Company:
def __init__(self, employee):
[Link] = employee
# def __iter__(self):
# return 1 # TypeError: iter() returned non-iterator of type 'int'
# def __iter__(self):
# return self # TypeError: iter() returned non-iterator of type 'Company'
# iter
# def __iter__(self):
# return iter([Link]) # <iterator object at 0x000001F512B907C8>
# MyIterator ******
def __iter__(self):
return MyIterator([Link]) # <__main__.MyIterator object at␣
,→0x0000013462EF0848>
( )
56 Chapter 9.
AdvancePython, 0.0.1
( )
return [Link][index]
if __name__ == '__main__':
company = Company(['linda', 'alex', 'catherine'])
my_iterator = iter(company)
print(my_iterator)
# for __iter__ __iter__ __getitem__
# for item in company:
# print(item)
while True:
try:
print(next(my_iterator))
except StopIteration:
break
"""
Company __next__ MyIterator
Company __iter__ MyIterator
"""
9.3 9.3
yield
• yield
def gen_func():
yield 1
yield 2
yield 3
#
( )
9.3. 9.3 57
AdvancePython, 0.0.1
( )
# 0 1 1 2 3 5 8 ...
def fib(index):
if index <= 2:
return 1
else:
return fib(index-1) + fib(index-2)
def func():
return 1
if __name__ == '__main__':
# python
gen = gen_func()
# for
for value in gen:
print(value)
ret = func()
• for
#
def fib(index):
if index <= 2:
return 1
else:
return fib(index-1) + fib(index-2)
#
def fib2(index):
ret_list = []
n, a, b = 0, 0, 1
while n < index:
ret_list.append(b)
a, b = b, a + b
n += 1
return ret_list
( )
58 Chapter 9.
AdvancePython, 0.0.1
( )
# yield
def gen_fib(index):
n, a, b = 0, 0, 1
while n < index:
yield b
a, b = b, a + b
n += 1
print(fib(10))
print(fib2(10))
for value in gen_fib(10):
print(value)
112358
9.4.1 python
import inspect
frame = None
def foo():
bar()
( )
( )
def bar():
global frame
frame = [Link]()
#
# import dis
# print([Link](foo))
foo()
print(frame.f_code.co_name) # bar
caller_frame = frame.f_back
print(caller_frame.f_code.co_name) # foo
( ) ;
60 Chapter 9.
AdvancePython, 0.0.1
9.4.2 python
def gen_func():
address = 'China'
yield 1
name = 'linda'
yield 2
age = 20
return 'done'
gen = gen_func()
import dis
print([Link](gen))
print(gen.gi_frame.f_lasti)
print(gen.gi_frame.f_locals)
• gen.gi_frame.f_lasti
• gen.gi_frame.f_locals
class MyList:
def __init__(self):
[Link] = []
62 Chapter 9.
AdvancePython, 0.0.1
( )
ll = MyList()
[Link](0, 1)
[Link](0, 2)
[Link](0, 3)
print([Link])
class MyDict:
def __init__(self):
[Link] = {}
dd = MyDict()
print([Link])
[Link](key1='value1', key2='value2')
print(dd['key1'])
print([Link])
collections
9.6 9.6
500G {|}
9.6. 9.6 63
AdvancePython, 0.0.1
( )
with open('input') as f:
for line in my_readline(f, '{|}'):
print(line)
9.7 9.7
64 Chapter 9.
CHAPTER 10
• ni-ning
• Email nining1314@[Link]
• [Link]
• GitHub [Link]
65
AdvancePython, 0.0.1
66 Chapter 10.
CHAPTER 11
Roadmap
2019/12/02 - 2019/12/31:
| github readthedocs
|
67