python学习day12 面向对象高级编程

#**********使用__slots__限制实例属性**********
class Student(object):
    pass
def set_age(self,age):
    self.age = age
from types import MethodType
s = Student()
s.set_age = MethodType(set_age,s)   #给实例绑定一个方法,只有本实例有这个方法,其他的实例没有
s.set_age(25)
print(s.age)

def set_score(self,score):      #通常情况下,set_score方法是直接定义在class中,但动态绑定允许我们在程序运行的过程中动态给class加上功能,这在静态语言中很难实现
    self.score = score
Student.set_score = set_score   #给class绑定方法,这样所有由Student创建的实例,都可以使用该方法
s1 = Student()
s.set_score(100)
print(s.score)
# 100
s1.set_score(99)
print(s1.score)
# 99
#为了达到限制的目的,比如,只允许对Student实例添加name和age属性,
# Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性
class Student(object):
    __slots__ = ("name","age")      #这样表示由Student创建的实例最多有"name" "age"两个属性
s = Student()
s.name = "perfey"   #绑定属性"name"
s.age = "24"        #绑定属性"age"
s.score = 99    #报错了,AttributeError: 'Student' object has no attribute 'score'

#使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
#除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__
class Student(object):
    def __init__(self,name):
        self.name = name
    __slots__ = "name"      #父类只允许name属性 ,如果没有这里的__slot__,后面Student的实例可以通过 s.score = 80 这样的方式来增加属性
class Student_son(Student):
    __slots__ = "age"       #子类这里允许的是 "age" 和 "name"属性,如果没有这里的__slot__,后面的Student_son的实例的属性没有限制

bart = Student_son("bart")
bart.age = 18
print(bart.age)     #18
bart.name = "afly"
print(bart.name)    #afly

猜你喜欢

转载自www.cnblogs.com/perfey/p/9205662.html