0% found this document useful (0 votes)
5 views73 pages

Advance Python

The document is a technical manual for 'AdvancePython' version 0.0.1, detailing various Python programming concepts and features. It includes sections on Python types, classes, decorators, and data structures such as lists and dictionaries. The content is organized into chapters with specific topics and examples to illustrate the concepts discussed.

Uploaded by

hexiaobing6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views73 pages

Advance Python

The document is a technical manual for 'AdvancePython' version 0.0.1, detailing various Python programming concepts and features. It includes sections on Python types, classes, decorators, and data structures such as lists and dictionaries. The content is organized into chapters with specific topics and examples to illustrate the concepts discussed.

Uploaded by

hexiaobing6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

AdvancePython

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

6 Python set dict 35


6.1 6.1 dict abc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.2 6.2 dict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
6.3 6.3 dict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
6.4 6.4 set frozenset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
6.5 6.5 dict set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
6.6 6.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

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 2.1 python

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

( )

print('Hello %s' % name)

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

Model Model get update delete

handle

def get_record_by_id(_id, handle=None):


record = [Link](id=_id)
if not record:
return False, ' '
if handle:
record = handle(record)
( )

6 Chapter 2. Python
AdvancePython, 0.0.1

( )

return True, record.to_dict

2.2 2.2 type object class

2.2.1 type

>>> name = 'linda'


>>> type(num)
<class 'int'>
>>> type(int)
<class 'type'>
>>> type(object)
<class 'type'>
>>> type(type)
<class '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__ ()

2.2. 2.2 type object class 7


AdvancePython, 0.0.1

2.2.3 type object class

• list dict

• object type

• type object

2.3 2.3 python

2.3.1

8 Chapter 2. Python
AdvancePython, 0.0.1

>>> name = 'linda'


>>> id(name)
2247760594928
>>> type(name)
<class 'str'>
>>> name
'linda'

2.3.2 python

• None( )

• int float complex bool

• list tuple str bytes

• dict

• set frozenset

• with

• class object type notimplemented

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

def __getitem__(self, index):


return [Link][index]

company = Company(['alex', 'linda', 'catherine'])


employee = [Link]

for item in employee:


( )

11
AdvancePython, 0.0.1

( )

print(item)

# for __iter__, __getitem__


for item in company:
print(item)

3.2 3.2 python

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 __add__(self, other):


return Vector(self.x + other.x, self.y + other.y)

def __str__(self):
return 'Vector(%s, %s)' % (self.x, self.y)

v1 = Vector(1, 3)
v2 = Vector(2, 4)
print(v1 + v2)

3.4 3.4 len

CPython list dict len(list)

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]()
"""

li1 = ['i1', 'i2']


li2 = ['i3', 'i4']

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 4.2 (abc )

4.2.1

• python

#
class Company:
def __init__(self, name):
[Link] = name

def __len__(self):
return len([Link])

company = Company('Linda Process Ltd.')


print(hasattr(company, '__len__'))

from [Link] import Sized


print(isinstance(company, Sized))

import abc

class CacheBase(metaclass=[Link]):

@[Link]
def get(self, key):
pass

@[Link]
def set(self, key, value):
pass

( )

4.2. 4.2 (abc ) 17


AdvancePython, 0.0.1

( )

class MemoryCache(CacheBase):
pass

Mixin

4.3 4.3 isinstance type

• 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

def __init__(self, x, y):


self.x = x
self.y = y
( )

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

• A -> B -> D -> C -> E

4.5. 4.5 19
AdvancePython, 0.0.1

• A -> B -> D -> C

• C D

20 Chapter 4.
AdvancePython, 0.0.1

4.5.3 BFS

• A -> B -> C -> D

4.5. 4.5 21
AdvancePython, 0.0.1

• A -> B -> C -> D -> E

• B D B D D C

4.5.4 MRO C3

class D:
pass

class C(D):
pass

class B(D):
pass

class A(B, C):


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

class A(B, C):


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

4.8 4.8 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))

4.9 4.9 super

4.8. 4.8 python 25


AdvancePython, 0.0.1

26 Chapter 4.
CHAPTER 5

Introduce

5.1 5.1 python

python

• list tuple deque

• str bytes bytearray [Link]

• list deque bytearray [Link]

• str tuple bytes

#
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')

5.2 5.2 abc

python [Link]

python

from [Link] import *

• Iterable: __iter__

• Reversible: __reversed__

• Sized: __len__

• Container: __contains__

• Collection: Sized, Iterable, Container

• Sequence: __getitem__, Reversible, Collection

• MutableSequence: __setitem__, __delitem__, Sequence

5.3 5.3 + += extend

• +

• +=

• 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 = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]


a_list[::] #
a_list[::-1] #
a_list[::2] #
a_list[1::2] #
a_list[3:6] #
a_list[0:100] #
a_list[100:] #

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 __getitem__(self, item):


cls = type(self)
if isinstance(item, slice):
return cls(group_name=self.group_name, company_name=self.company_name,␣
,→staff=[Link][item])
elif isinstance(item, [Link]):
return cls(group_name=self.group_name, company_name=self.company_name,␣
,→staff=[[Link][item]])

def __len__(self):
return len([Link])

def __iter__(self):
return iter([Link])

def __contains__(self, item):


if item in [Link]:
return True
else:
return False

( )

30 Chapter 5.
AdvancePython, 0.0.1

( )

staffs = ['linda', 'alex', 'catherine', 'nash', 'curry']


group = Group(group_name='group', company_name='company', staff=staffs)
sub_group = group[0]

print('linda' in sub_group)
print(len(sub_group))

5.5 5.5 bisect

• bisect

import bisect

#
#

l1 = list()
[Link](l1, 10)
[Link](l1, 3)
[Link](l1, 2)
[Link](l1, 6)

print(l1) # [2, 3, 6, 10]

5.6 5.6

• list python

• array

• deque

5.6.1 array

array list array

5.5. 5.5 bisect 31


AdvancePython, 0.0.1

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

odd_list = [handle_item(i) for i in range(21) if i % 2 == 1]


print(odd_list)

5.7.2

[] -> ()

my_gen = (i for i in range(21) if i % 2 == 1)


print(type(my_gen)) # <class 'generator'>
for i in my_gen:
print(i)

32 Chapter 5.
AdvancePython, 0.0.1

5.7.3

d1 = {'key1': 'value1', 'key2': 'value2'}


d2 = {v: k for (k, v) in [Link]()}
print(d2)

5.7.4

set1 = {v for v in [Link]()}


print(set1)

5.8 5.8

• abc

• + += extend

• bisect

• list

5.8. 5.8 33
AdvancePython, 0.0.1

34 Chapter 5.
CHAPTER 6

Python set dict

Introduce

6.1 6.1 dict abc

from [Link] import *

• Sized: __len__

• Iterable: __iter__

• Container: __contains__

• Collection: Sized, Iterable, Container

• Mapping: Collection

• MutableMapping: Mapping

dict list

from [Link] import Mapping

# dict Mapping
d = dict()
print(isinstance(d, Mapping))

35
AdvancePython, 0.0.1

6.2 6.2 dict

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)

dd = [Link](['key1', 'key2'], 'default')


[Link]('key', None)
[Link](), [Link](), [Link]()

# key value,
print([Link]('key', 'value'))
[Link]({'name': 'linda'})
print(dd)

6.3 6.3 dict

• c dict list

class MyDict(dict):
def __setitem__(self, key, value):
super().__setitem__(key, value * 2)

( )

36 Chapter 6. Python set dict


AdvancePython, 0.0.1

( )

my_dict = MyDict(one=1)
print(my_dict) # 1, __setitem__
my_dict['one'] = 1
print(my_dict) # 2, __setitem__

• UserDict

• python c

• defaultdict __missing__

from collections import defaultdict

d2 = defaultdict(list)
# __missing__ UserDict __getitem__
value = d2['key']
print(value)
print(dict(d2))

6.4 6.4 set frozenset

# set
s1 = set('abcc')
print(s1) # {'a', 'c', 'b'}

# frozenset dict key


f1 = frozenset('abcc')
print(f1)

6.5 6.5 dict set

6.6 6.6

6.4. 6.4 set frozenset 37


AdvancePython, 0.0.1

38 Chapter 6. Python set dict


CHAPTER 7

Introduce

7.1 7.1 python

• 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()

• ==

# is, id(a) id(b)


# =
a = [1, 2, 3, 4]
b = [1, 2, 3, 4]
print(a is b) # False, id
print(id(a), id(b))
print(a == b) # True, __eq__

# 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

7.3 7.3 del

# python

a = 1
b = a
del a

• del __del__

40 Chapter 7.
AdvancePython, 0.0.1

• 0

7.4 7.4

a, b

def add(a, b):


a += b
return a

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

def add(a, b):


a += b
return a

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

def add(a, b):


a += b
return a

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

( )

# a: (1, 2), b: (3, 4), c: (1, 2, 3, 4)


# a

class Company:
def __init__(self, name, staff_list=[]):
[Link] = name
self.staff_list = staff_list

def add(self, staff):


self.staff_list.append(staff)

def remove(self, staff):


self.staff_list.remove(staff)

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')

print(com2.staff_list) # ['staff2', 'staff3']


print(com3.staff_list) # ['staff2', 'staff3']

• [] com2.staff_list com3.staff_list

7.5 7.5

• python

• is == =

• del

42 Chapter 7.
CHAPTER 8

Introduce

8.1 8.1 property

from datetime import date

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 8.2 __getattr__ __getattribute__

8.2.1 __getattr__

class User:
def __init__(self, name):
[Link] = name

def __getattr__(self, item):


return 'Not found attribute %s' % item

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

def __getattr__(self, item):


( )

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

def __getattribute__(self, item):


return 'get_attribute'

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

def __get__(self, instance, owner):


print(instance) # <__main__.User object at 0x000002B88B270288>
print(owner) # <class '__main__.User'>
print(type(instance) is owner) # True
print(instance.__class__ is owner) # True
return self._data

def __set__(self, instance, value):


if not isinstance(value, [Link]):
raise ValueError('Need int value')
# value instance or self
# [Link] __set__
self._data = value

def __delete__(self, instance):


pass

class User:
age = IntField()
num = IntField()

if __name__ == '__main__':
user = User()
[Link] = 18
print(user.__dict__) # {} "age" __dict__

print([Link])

user [Link] getattr(user, 'age')

__getattribute__
( )

46 Chapter 8.
AdvancePython, 0.0.1

( )

__getattr__ __getattribute__ AttributeError __


,→getattr__
(__get__) __getattribute__

user = User(), [Link]


(1) 'age' User __dict__ age data descriptor __
,→get__(instance, owner)
(2) 'age' user __dict__ user.__dict__['age']
(3) 'age' User __dict__
(3.1) age non-data descriptor, __get__
(3.2) User.__dict__['age']
(4) User __getattr__ __getattr__
(5) AttributeError

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])

8.4 8.4 __new__ __init__

• __new__: self
__init__

• __init__:

• __new__ __init__

8.4. 8.4 __new__ __init__ 47


AdvancePython, 0.0.1

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

def __init__(self, name, age=18):


[Link] = name
[Link] = age
print('from __init__')

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

elif name == 'company':


class Company:
def __str__(self):
( )

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))

metaclass(type) -> class -> instance

class MetaClass(type):
# User User __new__
def __new__(cls, name, bases, attrs, **kw):
return super().__new__(cls, name, bases, attrs, **kw)

class User(object, metaclass=MetaClass):

def __init__(self, name):


[Link] = name

def bar(self):
print('from bar.')

8.5. 8.5 49
AdvancePython, 0.0.1

python user = User()

(1) metaclass User

(2) BaseUser metaclass User

(3) metaclass User

(4) type metaclass User

8.6 8.6 ORM

#
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

from collections import OrderedDict

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

( )

def __get__(self, instance, owner):


return self._value

def __set__(self, instance, value):


if not isinstance(value, int):
raise TypeError('need int value')
if value < self.min_value or value > self.max_value:
raise ValueError('need [%s, %s] value' % (self.min_value, self.max_value))
self._value = value

class CharField(Field):
def __init__(self, db_column, max_length=32):
self.db_column = db_column
self.max_length = max_length
self._value = None

def __get__(self, instance, owner):


return self._value

def __set__(self, instance, value):


if not isinstance(value, str):
raise TypeError('need str value')
if len(value) > self.max_length:
raise ValueError('len need lower than %s' % self.max_length)
self._value = value

#
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

( )

8.6. 8.6 ORM 51


AdvancePython, 0.0.1

( )

attrs_meta = [Link]('Meta', None)


_meta = {}
db_table = [Link]()
if attrs_meta is not None:
table = getattr(attrs_meta, 'db_table', None)
if not table:
db_table = table

_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

• __new__ __init__ __init__

8.7 8.7

8.7. 8.7 53
AdvancePython, 0.0.1

54 Chapter 8.
CHAPTER 9

Introduce

9.1 9.1 python

• Iterable

• Iterator

from [Link] import Iterable, Iterator


a = [1, 2]
print(isinstance(a, Iterable))
print(isinstance(a, Iterator))

9.2 9.2

__iter__ Iterator

55
AdvancePython, 0.0.1

from [Link] import Iterator

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>

def __getitem__(self, index):

( )

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
"""

• Comanpy for __iter__

• MyIterator next() __iter__ __next__

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 9.4 python

9.4.1 python

[Link] PyEval_EvalFrameEx(c ) foo


(stack_frame)

import inspect
frame = None

def foo():
bar()

( )

9.4. 9.4 python 59


AdvancePython, 0.0.1

( )

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

python foo foo bar


bar

( ) ;

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)

print('\nfirst value: %s' % next(gen))


print(gen.gi_frame.f_lasti)
print(gen.gi_frame.f_locals)

print('\nsecond value: %s' % next(gen))


print(gen.gi_frame.f_lasti)
print(gen.gi_frame.f_locals)

9.4. 9.4 python 61


AdvancePython, 0.0.1

• gen.gi_frame.f_lasti

• gen.gi_frame.f_locals

9.5 9.5 UserList

• from collections import UserList

class MyList:
def __init__(self):
[Link] = []

def __getitem__(self, index):


return [Link][index]

def __setitem__(self, index, value):


[Link][index] = value

def insert(self, index, item):


[Link](index, item)
( )

62 Chapter 9.
AdvancePython, 0.0.1

( )

ll = MyList()
[Link](0, 1)
[Link](0, 2)
[Link](0, 3)
print([Link])

• from collections import UserDict

class MyDict:
def __init__(self):
[Link] = {}

def __getitem__(self, item):


return [Link][item]

def __setitem__(self, key, value):


[Link][key] = value

def update(self, **kw):


for key, value in [Link]():
self[key] = value

dd = MyDict()
print([Link])

[Link](key1='value1', key2='value2')
print(dd['key1'])
print([Link])

collections

9.6 9.6

500G {|}

def my_readline(f, newline):


buf = ''
while True:
( )

9.6. 9.6 63
AdvancePython, 0.0.1

( )

while newline in buf:


pos = [Link](newline)
yield buf[:pos]
buf = buf[pos + len(newline):]
chunk = [Link](4096 * 10)
if not chunk:
yield buf
break
buf += chunk

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

You might also like