【Python】[面向对象高级编程] 使用__slots__,使用@property

1、使用 __slots__
    给实例绑定方法,

>>> def set_age(self, age): # 定义一个函数作为实例方法
...     self.age = age
...
>>>from types import MethodType
>>>s.set_age=MethodType(set_age,s)
>>>s.set_age(25)
>>>s.age
25

为了给所有的实例都绑定方法,可以给类绑定方法,

>>>def set_sore(self,score)
...    self.sore = score
...
>>>Student.set_sore = MethodType(set_score, Student)

这就是动态语言的特点,可以在运行中给程序加上功能
使用 __slots__ 来限制实例的属性,

class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称

2、使用@property

@property装饰器就是负责把一个方法变成属性调用,

原文地址:https://www.cnblogs.com/oiliu/p/4744998.html