成员的可见性:公开「public,在没进行成员私有操作前,变量和方法都是公开的」和私有「private,在变量和方法前加上__,变量和方法将不能被调用」
class Student():
nation = 'China'
def __init__(self, name, age):
self.name = name
self.age = age
self.__score = 0 #__score为私有变量
print(Student.nation) #类的内部调用变量
def do_homework(self):
self.do_English_homework() #类的内部调用方法
print('homework')
def do_English_homework(self):
print('English_homework')
def marking(self, score): #提倡通过方法来进行赋值,因为可以对输入的参数进行判断,如果不符合对变量的要求,超出了范围,可以保护数据
self.__score = score #__score为私有变量
if score < 60:
print('确定分数无误,下学期需多关注!')
else:
print(self.name + '同学本学期综合评分为:' + str(self.__score))
student1 = Student('hhh',18)
student2 = Student('xxx',18)
student1.do_homework() #类的外部调用方法
student1.nation #类的外部调用变量
student1.marking(58) #若marking()方法前加上__,变成__marking(),则无法完成调用
student1.__score = 15 #通过调用的方式,可以为实例对象新添加新的实例变量,但其他实例对象无法调用这个新添加的实例变量
print(student1.__score)
print(student2.__dict__)
print(student1.__dict__)
#输出结果
#China
#China
#English_homework
#homework
#确定分数无误,下学期需多关注!
#15
#{'name': 'xxx', 'age': 18, '_Student__score': 0}
#{'name': 'hhh', 'age': 18, '_Student__score': 58, '__score': 15} #私有变量名称被更改为'_Student__score',所以才能通过调用的方式,为实例对象新添加新的实例变量
类的继承性
class Human():
sum = 0
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
print(self.name)
def do_homework(self):
print('people should work')
class Student(Human):
def __init__(self, school, name, age):
self.school = school
#Human.__init__(self, name, age) #子类调用父类方法一,不推荐
super(Student, self).__init__(name, age) #子类调用父类方法二,推荐
def do_homework(self):
super(Student, self).do_homework() #实例方法中调用父类方法
print('homework')
student1 = Student('People road primary school', 'hhh', 8)
print(student1.name)
print(student1.age)
student1.do_homework()
#输出结果
#hhh
#8
#people should work
#homework