第六章:Python高级编程-对象引用、可变性和垃圾回收

第六章:Python高级编程-对象引用、可变性和垃圾回收

Python3高级核心技术97讲 笔记

目录
  • 第六章:Python高级编程-对象引用、可变性和垃圾回收
    • 6.1 Python中的变量是什么
    • 6.2 ==和is的区别
    • 6.3 del语句与垃圾回收
    • 6.4 一个经典的参数错误

6.1 Python中的变量是什么

#python和java中的变量本质不一样,python的变量实质上是一个指针 int str, 便利贴

a = 1
a = "abc"
#1. a贴在1上面
#2. 先生成对象 然后贴便利贴

a = [1,2,3]
b = a
print (id(a), id(b))
print (a is b)
# b.append(4)
# print (a)

6.2 ==和is的区别

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

print(a is b)
print(a == b)


# 对于比较小的Python不会重新创建
a = 1
b = 1
print(id(a), id(b))
print(a == b)
print(a is b)


class People:
    pass

person = People()  # 类是全局唯一的
if type(person) is People:
    print ("yes")
    

6.3 del语句与垃圾回收

#cpython中垃圾回收的算法是采用 引用计数
a = object()
b = a
del a
print(b)  # 有结果
print(a)  # 报错
class A:
    def __del__(self):  # del是Python会执行这个函数的逻辑
        pass

6.4 一个经典的参数错误

def add(a, b):
    a += b
    return a

class Company:
    def __init__(self, name, staffs=[]):
        self.name = name
        self.staffs = staffs
    def add(self, staff_name):
        self.staffs.append(staff_name)
    def remove(self, staff_name):
        self.staffs.remove(staff_name)

if __name__ == "__main__":
    com1 = Company("com1", ["bobby1", "bobby2"])
    com1.add("bobby3")
    com1.remove("bobby1")
    print (com1.staffs)

    com2 = Company("com2")
    com2.add("bobby")
    print(com2.staffs)

    print (Company.__init__.__defaults__)  # 查看默认值

    com3 = Company("com3")
    com3.add("bobby5")
    print (com2.staffs)
    print (com3.staffs)
    print (com2.staffs is com3.staffs)  # 没有传入,使用默认的值,所以共用了

    # a = 1
    # b = 2
    #
    # a = [1,2]  # a是可变的哦
    # b = [3,4]
    #
    # a = (1, 2)
    # b = (3, 4)
    #
    # c = add(a, b)
    #
    # print(c)
    # print(a, b)

你可能感兴趣的:(第六章:Python高级编程-对象引用、可变性和垃圾回收)