面向对象编程---使用__slots__

学习廖雪峰老师的python教程中的使用__slots__的笔记:

第一部分:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Student(object):
    pass

s=Student()
s.name=('Michael')#给实例绑定属性
print(s.name)

##########给实例绑定方法##############
def set_age(self,age):
    self.age=age
from types import MethodType
s.set_age=MethodType(set_age,s)#给s绑定set_age方法
s.set_age(25)
s2 = Student()
#s2.set_age(25) #给一个实例绑定的方法对另一个实例是不起作用的,不注释掉程序会卡在这里
print("the age of s is:",s.age)
#print("the age of s2 is:",s2.age)

#############给class绑定方法,所有实例都可用#############
def set_score(self, score):
    self.score = score
Student.set_score = set_score
s.set_score(100)
print("the score of s is:",s.score)
s2.set_score(99)
print("the score of s2 is:",s2.score)

第二部分:使用__slots__

Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性:

__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
    
s = Student() # 创建新的实例
s.name = 'Michael' # 绑定属性'name'
print("the name of s is",s.name)
s.age = 25 # 绑定属性'age'
print("the age of s is",s.age)
#s.score = 99 # 绑定属性'score',应该是不成功的,因为 __slots__中不包含score属性
#print("the score of s is",s.score)


###################__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:###################
class GraduateStudent(Student):
    pass
g=GraduateStudent()
g.score=900
print("the score of s is",g.score)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值