针对定义的类中 有些属性不希望被外部访问的情况
Python对属性权限的控制是通过属性名来实现的,如果一个属性由双下划线开头(__),该属性就无法被外部访问。
栗子1:
class Person(object):
def __init__(self, name):
self.name = name
self._title = 'Mr'
self.__job = 'student'
p = Person('Bob')
print(p.name)
print(p._title)
Bob
Mr
但是,当访问 print(p.__job) 时,出错如下:
AttributeError: ‘Person’ object has no attribute ‘__job’
但是,如果一个属性以"_xxx_“的形式定义,那它又可以被外部访问了,以”_xxx_“定义的属性在Python的类中被称为特殊属性,有很多预定义的特殊属性可以使用,通常我们不要把普通属性用”_xxx_"定义
print(p.job)
结果为: student
以单下划线开头的属性"_xxx"虽然也可以被外部访问,但是,按照习惯,他们不应该被外部访问
任务:
给Person类的__init__方法中添加name和score参数,并把score绑定到__score属性上,看看外部是否能访问到。
class Person(object):
def __init__(self, name, __score):
self.name = name
self.__score = __score
p = Person('Bob', 59)
print(p.name)
try:
print(p.__score)
except:
print("AttributeError")
结果为:
Bob
AttributeError