【Python】学习笔记八:面向对象
2024-09-01 19:24:14
举例
面向对象的合理解释就是:我是人这个类,对象化以后我就是一个个体OLIVER
对象化就是在人这个大类中,将某个人指名道姓,具体到某个人
下面是一个具体的实例一:
#!/usr/bin/python
#-*- coding:UTF-8 -*-
class CompanyMember:
#总人数,这个类的变量
MemberCount = 29
#__ini__方法在类的对象被创建时候执行
def __init__(self,name):
self.name = name
CompanyMember.MemberCount +=1
print ("公司来了一个新成员:%s" % self.name)
print ("现有成员%d人" % CompanyMember.MemberCount)
#新建一个方法,新员工介绍
def introduce(self):
print("我的名字叫做:%s" % self.name) #领导继承公司成员类
class Leader(CompanyMember):
def __init__(self,name,salary):
CompanyMember.__init__(self,name)
self.salary = salary
self.name=name
def introduce(self):
CompanyMember.introduce(self)
print("%s是领导:我的工资是%d" % (self.name,self.salary)) #部门经理继承公司成员类
class Manager(CompanyMember):
def __init__(self,name,Location):
CompanyMember.__init__(self,name)
self.Location=Location
self.name=name
def introduce(self):
CompanyMember.introduce(self)
print("%s是%s部门的部门经理" % (self.name,self.Location))
# 创建一个新员工对象
CompanyMember1=CompanyMember("OLIVER")
CompanyMember1.introduce()
print("--------------------------")
#创建一个领导对象
Leader1=Leader("jack",360000)
Leader1.introduce()
print("--------------------------")
#创建一个部门经理对象
Manager1=Manager("john","Sales")
Manager1.introduce()
实例二:
#!/usr/bin/python
#-*- coding:UTF-8 -*- 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)
"#创建 Employee 类的第一个对象"
emp1=Employee("OLIVER","") "创建 Employee的第二个对象"
emp2=Employee("QIN",'') emp1.displayEmployee()
emp2.displayEmployee() print ("Total Employee %d" % Employee.empCount)
总结
将东西根据属性归类 ( 将object归为class )
方法是一种属性,表示动作
用继承来说明父类-子类关系。子类自动具有父类的所有属性。
self代表了根据类定义而创建的对象。
建立对一个对象: 对象名 = 类名()
引用对象的属性: object.attribute
最新文章
- 《徐徐道来话Java》:PriorityQueue和最小堆
- (转)windows系统下Python环境的搭建
- 转载:《TypeScript 中文入门教程》 2、枚举
- How to use aws CloudFront for CDN
- wmic 命令的一个汇总,功能很强大
- Emule Xtreme Kid eD2K 设置
- Nginx reopen reload作用及工作过程
- RDMA的ibv_post_send() 函数
- ASP.NET上传大文件的问题
- java.sql.SQLException: null, message from server: “Host ‘xxx’ is not allowed to connect
- 怎样搭建本地svn服务器环境-轻松掌握版本管理
- [转]fedora启动telnet服务
- @Component @Repository @Service @Controller
- The calculation of GPA
- Linux---More命令 初级实现
- LINUX 内核调试基础+编程基础
- Anaconda更新源
- k8s Kubernetes v1.10
- 学JAVA第十天,一维数组及二维数组的使用。
- Spark Standalone spark-env.sh