Python some error-prone small detail records

1.python collection run (-, &, |, ^)

a = {
    
    1, 2, 3, 4, 5}
b = {
    
    5, 6}
# 集合a中包含而集合b中不包含的元素
print(a - b)  # {1, 2, 3, 4}

# 集合a和b中都包含了的元素
print(a & b)  # {5}

# 集合a或b中包含的所有元素  
print(a | b)  # {1, 2, 3, 4, 5, 6}

# 不同时包含于a和b的元素
print(a ^ b)  # {1, 2, 3, 4, 6}

2. The default parameters of python

Python's default parameters have a pit, called below, the default parameters are only initialized once.
Variable default parameter case:

def func(v, L=[]):
	print("address of L:", id(L))  # 地址
    L.append(v)
    return L


print(func('1'))  
print(func('2'))

"""输出:
address of L: 2819974003528
['1']
address of L: 2819974003528
['1', '2']   # 是不是和预想的不一样,'2'被直接加到了第一次初始化的列表上
"""

Default immutable parameter case:

def func(i=1):
    print('before address of i', id(i))
    i += 1
    print('after address of i', id(i))
    return i


print(func())
print("=========")
print(func())

"""
输出:
before address of i 1910795296
after address of i 1910795328
2
=========
before address of i 1910795296  
after address of i 1910795328
2
"""

3. The difference between == and is

== is used to determine whether the values ​​​​of reference variables are equal. Only judge the value and data type
is is used to judge whether the two variable reference objects are the same, that is, whether the memory addresses of the referenced objects are consistent

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print("id(a) =", id(a))  # id(a) = 2224767619592
print("id(b) =", id(b))  # id(b) = 2224767619592
print("id(c) =", id(c))  # id(c) = 2224767597384

print(a == b)  # True
print(a == c)  # True
print(a is b)  # True
print(a is c)  # False
print(b is c)  # False

4. Use isinstance for type judgment instead of type()

class Foo():
    pass


class Bar(Foo):
    pass


print(type(Foo()) == Foo)  # True
print(type(Bar()) == Foo)  # False
print(isinstance(Foo(), Foo))  # True
print(isinstance(Bar(), Foo)) # True

Guess you like

Origin blog.csdn.net/weixin_45455015/article/details/119080948