极客编程python入门-类访问限制
原创
©著作权归作者所有:来自51CTO博客作者最爱大苹果的原创作品,请联系作者获取转载授权,否则将追究法律责任
类的访问限制
如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问
这样就确保了外部代码不能随意修改对象内部的状态,这样通过访问限制的保护,代码更加健壮。
代码:
class Applea(object):
def __init__(self,name,age):
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def set_name(self,name):
self.__name = name
def set_age(self,age):
self.__age = age
A = Applea('EVE',21)
print(A.get_name())
print(A.get_age())
A.set_age(22)
A.set_name("CAT")
print(A.get_name(),A.get_age())
效果:
但是如果外部代码要获取name和score怎么办?可以给Student类增加get_name和get_score这样的方法:
class Student(object):
...
def get_name(self):
return self.__name
def get_score(self):
return self.__score
如果又要允许外部代码修改score怎么办?可以再给Student类增加set_score方法:
class Student(object):
...
def set_score(self, score):
self.__score = score