'''面向对象编程python对象中的方法和属性私有使用__定义,但是私有属性可以使用obj._ClassName.__attr访问(函数一样) 使用关键字class定义'''class Student(object):__score = 0# __init__是一个特殊方法用于在创建对象时进行初始化操作 self为类实例相当于java中的this# 通过这个方法我们可以为学生对象绑定name和age两个属性def __init__(self, name, age, score):self.name = nameself.age = ageself.__score = scoredef study(self, course_name):print('%s正在学习%s' % (self.name, course_name))# PEP 8要求标识符的名字用全小写多个单词用下划线连接# 但是部分程序员和公司更倾向于使用驼峰命名法(驼峰标识)def watch_movie(self):if self.age < 18:print('%s只能观看《熊出没》.' % self.name)else:print('%s正在观看岛国爱情大电影.' % self.name)def __eat(self):print("吃东西,这是私有的")class Employee:'所有员工的基类'empCount = 0def __init__(self, name, salary):self.name = nameself.salary = salaryEmployee.empCount += 1def displayCount(self):print("Total Employee %d" % Employee.empCount)def displayEmployee(self):print("Name : ", self.name, ", Salary: ", self.salary)print('Employee.__doc__:', Employee.__doc__) # 所有员工的基类print("Employee.__name__:", Employee.__name__) # Employeeprint("Employee.__module__:", Employee.__module__) # __main__print("Employee.__bases__:", Employee.__bases__)print("Employee.__dict__:", Employee.__dict__)def main():stu1 = Student('张三', 29, 90)stu1.study('Python程序设计')stu1.watch_movie()stu1 = Student('李四', 16, 86)stu1.study('世界历史')stu1.watch_movie()# print(stu1.__score) # 访问私有变量报错print(stu1._Student__score)#stu1.__eat() # 访问私有方法报错stu1._Student__eat()if __name__ == '__main__':main()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。