Python中私有變量和私有方法芳
? ??
? ? Python中要想定義的方法或者變量只能在類內(nèi)部使用不被外部使用,可以在方法和變量前面加兩個下劃線,讓其變?yōu)樗接蟹椒ɑ蛩接凶兞?。類外部可以通過 ”_類名__私有屬性(方法)名“ 訪問私有屬性(方法)。
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
? ? 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
? ? 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
? ? print(test1.__age)
AttributeError: 'Person' object has no attribute '__age'
__work是私有類變量,__age是私有實例變量,類內(nèi)是可以訪問的
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
? ? 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
