Python中私有变量和私有方法芳

王大力测试进阶之路

共 1898字,需浏览 4分钟

 ·

2022-04-24 22:07

    

    Python中要想定义的方法或者变量只能在类内部使用不被外部使用,可以在方法和变量前面加两个下划线,让其变为私有方法或私有变量。类外部可以通过 ”_类名__私有属性(方法)名“ 访问私有属性(方法)。


class Person:    __work = 'teacher'
def __init__(self,name,age): self.name = name self.__age = age
def 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是私有实例变量,类内是可以访问的

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


浏览 30
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报