python 中所有的数据类型都是,数据都是对象
所有的运算符对应的操作,本质都是在调用数据类型对应的魔法方法(每个运算符都对应一个固定的魔法方法)
class Student:
def __init__(self, name, age = 0, score = 0):
self.name = name
self.age = age
self.score = score
def __str__(self):
return self.__dict__
def __add__(self, other):
return self.age + other.age
def __mul__(self, other):
result = []
for _ in range(other):
result.append(self)
return result
stu1 = Student('小明', 18, 90)
stu2 = Student('小王', 22, 80)
print(stu1+stu2)
练习: 让Student的对象支持乘法运算,运算规则是:
stu * 3 = [stu , stu, stu]
print(stu1 * 3)
```python
import copy
class Student:
def __init__(self, name, age=0, score=0):
self.name = name
self.age = age
self.score = score
def __repr__(self):
return '<'+str(self.__dict__)[1:-1]+'>'
def __mul__(self, other):
result = []
for _ in range(other):
result.append(self)
return result
stu1 = Student('小明', 18, 90)
1. 一个变量直接给另外一个变量赋值:直接将地址赋值,敷完之后两个变量指向同一块内存区域,并且相互影响
拷贝原理:将拷贝的对象赋值一份,产生一个新的
'''
浅拷贝
- 列表或者字典的copy方法是浅拷贝、切片也是浅拷贝
2) copy.copy(对象) --- 复制指定对象,产生一个新的对象
深拷贝
copy.deepcopy() --- 复制指定的对象,产生一个新的对象。如果这个对象中有其他的对象,子对象也会被复制
1.数据的存储(内存开辟)
栈区间
所有的 变量 都在栈区间。
函数调用过程中
堆区间
所有的数据/对象 都在堆区间
声明变量或者给变量赋值,是先在内存(堆区间)中开辟存储数据,然后将数据地址保存在变量中
数字和字符串 比较特殊,如果使用数字或者字符串给变量赋值,不会直接开辟空间保存数据,而是先在
内存中检查这个数据之前是否已经存储过,如果已经存储直接用上次保存的数据,没有存储才会开辟新的空间保存数据,
2 内存的释放
"""
引用计数
python每个对象都有一个熟悉交引用计数,用来保存当前对象的引用的个数
python中的垃圾回收机制来判断一个对象是否销毁,就看这对象的引用计数是否为零,如果为零就会被销毁。
from sys import getrefcount # 获取引用计数的函数声明
# 让引用计数增加
list1 = [1,2,3]
print(getrefcount(list1))
dict1 = {'a': 'abc'}
list2 = list1
print(getrefcount(list2))
num1 = 0
print(getrefcount(num1))
# 让引用计数减少
list1 = 99
del dict1['a']