平常都没注意python是如何将属性和方法设置成私有的,今天看到了就记一下。
要想将属性和方法设置成私有的,只需要在属性前面或者方法前面加上__(注意,是双下划线)。
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def __printStudent(self):
print("姓名是:",self.name)
print("年龄是:",self.age)
stu = Student("tom",12)
#当将printStudent设置成私有的方法时
#再去在类外访问该方法就会报错
stu.printStudent()
但是呢,在Python中是没有真正意义上的私有属性和方法的,为什么这么说呢?
因为在给属性或方法命名时,实际上是对名称进行了一些特殊的处理,使得外界无法访问。
我们可以使用以下方法来获取私有的属性和方法:
stu._Student__printStudent()
即实例化的对象.单下划线+类名+方法名。