__xxx
#!/usr/bin/python3
#-*- coding:utf-8 -*-
class Student:
def __init__(self,name,score):
self.name = name
self.__score = score #将score隐藏起来,使之仅在类内部可用。
def __show(self): #一个隐藏的方法,同样只在内部可用
print(self.name,self.__score)#使用被隐藏的属性__score
def Show(self):
self.__show() #注意被隐藏方法的调用方式。
def main():
he = Student('Bob',95)
he.Show() #显示:Bob 95
#print(he.__score) #AttributeError: 'Student' object has no attribute '__score'
#he.__show() #AttributeError: 'Student' object has no attribute '__show'
#隐藏属性真的被隐藏了吗?其实仍然可使用,使用格式 obj._className__attributeName
#但是仅仅作为了解,不建议使用隐藏属性。
print(he._Student__show()) #显示:Bob 95
print(he._Student__score) # 显示: 95
if __name__=="__main__":
main()
#!/usr/bin/python3
#-*- coding:utf-8 -*-
class Student:
def __init__(self,name,score):
self.name = name
self.score = score
@property #实现属性的读取方法,读取实例的score值时,就会调用这个函数
def score(self):
return self.__score
@score.setter #实现属性写入方法,写入实例的score属性时,调用这个函数
def score(self,newVal):
if not isinstance(newVal,(int,float)):
raise TypeError('score value must be a number')
if newVal>100 or newVal<0:
raise ValueError('score value must between 0 and 100')
self.__score = newVal
def main():
he = Student('Bob',95)
he.score = 100 #重新写入
print(he.score) #读取
if __name__=="__main__":
main()
#!/usr/bin/python3
#-*- coding:utf-8 -*-
class Student:
def __init__(self,name,score):
self.name = name
self.score = score
def main():
he = Student('Bob',95)
he.age = 19
print(he.age)
if __name__=="__main__":
main()
使用__slots__
#!/usr/bin/python3
#-*- coding:utf-8 -*-
class Student:
__slots__ = ('name','score') #将属性名以字符串形式加入元组
def __init__(self,name,score):
self.name = name
self.score = score
def main():
he = Student('Bob',95)
he.age = 19 #AttributeError: 'Student' object has no attribute 'age'
print(he.age)
if __name__=="__main__":
main()
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有