Python进阶1-面向对象之类和实例
1.类和实例
__slots__ 限制实例能添加的属性,减少实例占用内存(__dict__属性字典改为元组)
- Python的很多特性都依赖于普通的基于字典的实现。
- 作为内存优化工具而不是封装工具
- 为了让对象支持弱引用 ,必须有
__weakref_ 属性。
- 定义了slots后的类不再支持多继承
__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) print(s.name, s._age, s._Student__sex) s._getage() s._Student__getsex() s.func1() Student.func1() Student.func2('aya', 18, 'girl')
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
| class Student(object): def __init__(self, birth): self._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
@property def age(self): return 2020 - self._birth
s = Student(2000) print(s.birth) s.birth = 2002 print(s.birth) print(s.age)
del s.birth
|