Python中要想定义的方法或者变量只能在类内部使用不被外部使用,可以在方法和变量前面加两个下划线,让其变为私有方法或私有变量。类外部可以通过 ”_类名__私有属性(方法)名“ 访问私有属性(方法)。
class Person:__work = 'teacher'def __init__(self,name,age):self.name = nameself.__age = agedef run(self):print(self.__age,self.__work)def __eat(self):print('1111')
__work是私有类变量,类外是无法访问的
if __name__ == '__main__':
print(Person.__work)
Traceback (most recent call last):File "C:/Users/wangli/PycharmProjects/Test/test/test.py", line 20, in <module>print(Person.__work)
AttributeError: type object 'Person' has no attribute '__work'
__work是私有类变量,类外类实例对象是无法访问的
if __name__ == '__main__':test1 = Person('王大力','22')
print(test1.__work)
Traceback (most recent call last):File "C:/Users/wangli/PycharmProjects/Test/test/test.py", line 21, in <module>print(test1.__work)
AttributeError: 'Person' object has no attribute '__work'
__age是私有实例变量,类外类实例对象是无法访问的
if __name__ == '__main__':test1 = Person('王大力','22')
print(test1.__age)
Traceback (most recent call last):File "C:/Users/wangli/PycharmProjects/Test/test/test.py", line 21, in <module>print(test1.__age)
AttributeError: 'Person' object has no attribute '__age'
__work是私有类变量,__age是私有实例变量,类内是可以访问的
if __name__ == '__main__':test1 = Person('王大力','22')
test1.run()
22 teacher
Process finished with exit code 0
__eat()是私有方法,类外是无法访问的
if __name__ == '__main__':test1 = Person('王大力','22')
print(test1.__eat())
Traceback (most recent call last):File "C:/Users/wangli/PycharmProjects/Test/test/test.py", line 21, in <module>print(test1.__eat())
AttributeError: 'Person' object has no attribute '__eat'
__work是私有类变量,__age是私有实例变量,__eat()是私有方法,类外部可以通过 ”_Person___私有属性(方法)名“ 访问私有属性(方法)
if __name__ == '__main__':print(Person._Person__work)test1 = Person('王大力','22')print(test1._Person__work)print(test1._Person__age)
test1._Person__eat()
teacher
teacher
22
1111
Process finished with exit code 0