成员可见性:公开和私有
class Student():
sum = 0
def __init__(self,name,age):
self.name = name
self.age = age
self.score = 0 # 表示实例下有score这么一个变量
def marking(self,score):
if score < 0:
print("不能给别人打负分")
score = 0
self.score = score
print(s1.name+"这次考试考了"+ str(s1.score) + "分")
def do_math_homework(self):
pass
def do_english_homework(self):
pass
s1 = Student("安琪拉",12)
# s1.marking(50)
s1.marking(-1)
# 不要在类的外部直接对成员变量作赋值操作(哪怕可以这么做),推荐使用方法,方法的好处,就是可以添加逻辑处理
不能给别人打负分
安琪拉这次考试考了0分
上面的代码在类外仍然可以对score进行访问读取和修改,很危险, 怎么解决呢?
- public: 公有的
- private: 私有的
在python里面如何设置共有和私有?
在python中,如果变量和方法前面有2个下划线,就表示私有:
class Student():
__sum = 0
def __init__(self,name,age):
self.name = name
self.age = age
self.score = 0 # 表示实例下有score这么一个变量
def marking(self,score):
if score < 0:
print("不能给别人打负分")
score = 0
self.score = score
print(s1.name+"这次考试考了"+ str(s1.score) + "分")
def do_math_homework(self):
pass
def do_english_homework(self):
pass
s1 = Student("安琪拉",12)
# s1.marking(50)
s1.marking(-1)