Python进阶1-面向对象之类和实例

1.类和实例

__slots__ 限制实例能添加的属性,减少实例占用内存(__dict__属性字典改为元组)

  1. Python的很多特性都依赖于普通的基于字典的实现。
  2. 作为内存优化工具而不是封装工具
  3. 为了让对象支持弱引用 ,必须有__weakref_ 属性。
  4. 定义了slots后的类不再支持多继承
  5. __slots__定义的属性仅对当前类实例起作用,对继承的子类不起作用;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Student(object):
score = 100 # 类的基本属性
__math = 10 # 类的私有属性,__开头的属性和方法因为改名,继承时不会被覆盖

__slots__ = ('name', '_age', '__sex')

def __init__(self, name, age, sex):
self.name = name
self._age = age # 约定的私有属性
self.__sex = sex # 私有属性

# 约定的私有方法
def _getage(self):
print("age: ", self._age)

# 私有方法
def __getsex(self):
print('sex: ', self.__sex)

# 静态方法
@staticmethod
def func1():
print('staticmethod');

# 类方法
@classmethod
def func2(cls, name, age, sex):
print(cls.score) # 调用类属性
cls(name, age, sex).func1() # 调用静态方法

s = Student('aya', 18, 'girl')
print(s.score, s._Student__math) # 100 10 访问类属性
print(s.name, s._age, s._Student__sex) # aya 18 girl 访问实例属性
s._getage() # age: 18
s._Student__getsex() # sex: girl 实例调用私有方法
s.func1() # staticmethod 实例调用静态方法
Student.func1() # staticmethod 类调用静态方法
Student.func2('aya', 18, 'girl') # 100 类调用类方法

print(Student.__dict__) # 类的属性字典
print(Student.__doc__) # 类的文档字符串
print(Student.__name__) # 类名
print(Student.__module__) # 类定义所在的模块
print(Student.__bases__) # 类的所有父类组成的元组

2.property

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# property
class Student(object):
def __init__(self, birth):
self._birth = birth

# birth是可读写属性
@property
def birth(self):
return self._birth

@birth.setter
def birth(self, value):
self._birth = value

@birth.deleter
def birth(self):
print("删除属性")
del self._birth

# age是只读属性
@property
def age(self):
return 2020 - self._birth

s = Student(2000)
print(s.birth) # 2000
s.birth = 2002
print(s.birth) # 2002
print(s.age) # 18

del s.birth