Python私有变量的定义与访问

class Student():
	def __init__(self, name, age):
		self.name = name
		self.age = age
		self.__score = 0

	def marking(self, score):
		if score < 0:
			return '分数不能为0'
		self.__score = score
		print(self.name + '同学本次得分是:' + str(self.__score))	

	def __talk(self): # 私有的类可通过在前面加__即可
		print('私聊我')	

  
    
student1 = Student('喜小乐', 18)    
student1.marking(70)
# student1.talk() # 会报错
student1._Student__talk()
student1.__score = 20
print(student1.__score)
print(student1.__dict__)

student2 = Student('石敢当', 18)    
print(student2.__dict__)

print('***********************')
print(Student.__dict__)

打印结果如下:
Python私有变量的定义与访问_第1张图片

你可能感兴趣的:(python,开发语言)