Python类:成员的可见性

成员的可见性:公开「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            
      

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值