一:私有属性
class PersonDemo(): # 私有类属性 __age = 10 def __init__(self): # 私有实例属性 self.__weight = 100
二:访问私有属性
from python知识点 import Person p = Person.PersonDemo() print(p.__age) print(p.__weight) # 结果 Traceback (most recent call last): File "F:/pycharm测试功能文件夹/python知识点/Use_Person.py", line 4, in <module> print(p.__age) AttributeError: ‘PersonDemo‘ object has no attribute ‘__age‘
访问类的私有属性,get方法
class PersonDemo(): # 私有类属性 __age = 10 def __init__(self): # 私有实例属性 self.__weight = 100 def get__age(self): return self.__age def get__weight(self): return self.__weight
from python知识点 import Person p = Person.PersonDemo() age_result = p.get__age() weight_result = p.get__weight() print(age_result,weight_result) # 结果 10 100
# TODO
原文:https://www.cnblogs.com/meloncodezhang/p/12836501.html