1 Star 0 Fork 0

caifan/python_learn

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
object_01.py 2.09 KB
一键复制 编辑 原始数据 按行查看 历史
caifan 提交于 2023-11-24 10:57 +08:00 . 类继承多态
'''
面向对象编程
python对象中的方法和属性私有使用__定义,但是私有属性可以使用obj._ClassName.__attr访问(函数一样) 使用关键字class定义
'''
class Student(object):
__score = 0
# __init__是一个特殊方法用于在创建对象时进行初始化操作 self为类实例相当于java中的this
# 通过这个方法我们可以为学生对象绑定name和age两个属性
def __init__(self, name, age, score):
self.name = name
self.age = age
self.__score = score
def 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 = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def 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__) # Employee
print("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()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/sharehappy/python_learn.git
git@gitee.com:sharehappy/python_learn.git
sharehappy
python_learn
python_learn
master

搜索帮助