20/01/20 Python基础知识学习(8)

面向对象编程OOP

  • 静态函数
    与实例无关:def func(无需self):

  • 计数-类的计数,与实例无关

class Book:
	count = 0
	def __init__(self, a, b):
		self.a=a
		self.b=b
		return
  • 计数-实例自身的计数
class Book:
	count = 0
	def __init__(self, a, b):
		self.a=a
		self.b=b
		count+=1
		return
a = Apple()
a.count = 5
print(Apple.count) # 输出1
print(a.count1) # 输出5
  • 特殊的函数:
    __init__初始化
    __repr__定义在控制台上的表现。程序员在调试时,特别是循环打印时需要的简略的信息
    __str__普通用户看得到,使用print( 对象名)显示,如果无str显示repr内容
    __del__执行删除

  • 类属性声明(代替某一类的方法)
    @property

@property
def age(self): 函数体 # age即类属性,可直接调用实例的属性,不必调用函数

- 类属性设置声明
@属性名.setter
```python
@age.settter
def age(self, value): 函数体 # 重新赋值时执行
  • 类属性删除声明
    @属性名.deleter
@age.deleter
def age(self): 函数体 # 删除该属性时执行
  • 继承:如果多个类有重叠的部分,在一定程度上实现代码重用
    继承实例:
import datetime
class Employee():
	def __init__(self,department,name,birthday,salary):
		self.department=department
		self.name=name
		self.birthday=birthday
		self.salary=salary

	@property
	def age(self):
		return datetime.date.today().year-self.birthday.year

	def get_raise(self,percent,bonus=.0):
		self.salary=self.salary *(1+percent+bonus)
		
	def __repr__(self):
		return '<员工:{}>'.format(self.name)

	def __working__(self):
		print('<员工{},在工作...>'.format(self.name))

class Programer(Employee):
	def __init__(self,department,name,birthday,salary,specialty,project):
		super().__init__(self,department,name,birthday,salary)
		self.specialty=specialty
		self.project=project

	def __working__(self):  #多态
		print('<程序员{},在开发项目:{}...>'.format(self.name,self.project))

class Hr(Employee):
	def __init__(self,department,name,birthday,salary,qualification_level=1)
		employee.__init__(self,department,name,birthday,salary) #多层避免误解不要用super()
		self.qualification_level=qualification_level

if __name__='__main__':
	p=Programer('技术部','Peter',datetime.date(1990,3,1),8000,'python','CRM')

	p  #返回  <员工:Peter>
	p.salary  #返回  8000
	p.get_raise(.2)
	print(p.salary)  #返回9600
	print(p,age)  #返回30
  • 多态:属于同一类型的不同实例,对同一消息做出不同的相应
    多态实例(续上):
class Department():	
	def __init__(self,department,phone,manager):
		self.department=department
		self.phone=phone
		self.manager=manager
...
dep=Department('技术部',12345678,‘张三’)
p=Programer(dep,'Peter',datetime.date(1990,3,1),8000,'python','CRM')
p.get_raise(.2,.1)
print(p.department)  #返回类的实例
		

发布了10 篇原创文章 · 获赞 0 · 访问量 164

猜你喜欢

转载自blog.csdn.net/weixin_44602323/article/details/104055513