高端集团网站建设公司,手机评测网站,网站制作需要平台,六盘水住房和城乡建设部网站Python中要想定义的方法或者变量只能在类内部使用不被外部使用#xff0c;可以在方法和变量前面加两个下划线#xff0c;让其变为私有方法或私有变量。类外部可以通过 ”_类名__私有属性#xff08;方法#xff09;名“ 访问私有属性#xff08;方法#xff09;。class P… Python中要想定义的方法或者变量只能在类内部使用不被外部使用可以在方法和变量前面加两个下划线让其变为私有方法或私有变量。类外部可以通过 ”_类名__私有属性方法名“ 访问私有属性方法。class Person:__work teacherdef __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 moduleprint(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 moduleprint(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 moduleprint(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 moduleprint(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