本章将学会OOP思想,定义类,方法,继承,多态
文章目录
OOP思想(Object Oriented Programming)
面向对象编程,简单来说,对象是特征和行为集合体,也可以说静态属性和动态行为集合体,也是对现实的描述和模拟,比如说 猫,特性:品种,大小,毛发形状,毛发颜色,四肢, 行为:喵喵叫,抓老鼠,这些特征和行为集合体称之为猫。
1、Python类
1.1、Objects(对象)
- 万物皆对象
- 比如我可以使用type()方法去检查对象类型
"""
<class 'int'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
"""
print(type(1))
print(type([]))
print(type(()))
print(type({}))
1.2、Class(类)
- 可以认为这个一份蓝图或者模板
- 语法:class 类名: 属性和方法
# pass 表示没有任何实现
class Sample:
pass
- init 内置构造初始化方法
- self 表示本对象
class Dog:
# 类级别属性
species = 'mammal'
def __init__(self, breed, name):
self.breed = breed
self.name = name
sam = Dog('Lab', 'Sam')
print(Dog.species)
# 定义一个圆
class Circle:
pi = 3.14
# 圆默认半径为1
def __init__(self, radius =1):
self.radius = radius
self.area = radius **2 * Circle.pi
# 重新设置半径
def setRadius(self, new_radius):
self.radius = new_radius
self.area = new_radius * new_radius * self.pi
# 计算周长
def getCircumference(self):
return self.radius * self.pi * 2
c = Circle()
print('Radius is: ', c.radius)
print('Area is: ', c.area)
print('Circumference is: ', c.getCircumference())
# 重新设置半径为2
c.setRadius(2)
print('Radius is: ', c.radius)
print('Area is: ', c.area)
print('Circumference is: ', c.getCircumference())
1.2.1、继承(Inheritance)
- 语法: class 子类名(父类)
# Dog 继承Animal 的类, 重写whoAmI方法
class Animal:
def __init__(self):
print("Animal created")
def whoAmI(self):
print("Animal")
def eat(self):
print("Eating")
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print("Dog created")
def whoAmI(self):
print('Dog')
def bark(self):
print("Woof!")
d = Dog()
d.whoAmI()
d.eat()
d.bark()
1.2.2、多态,同一个方法名,不同行为
# 比如 Dog 和Cat 叫声是不一样
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return self.name+ ' says Woof!'
class Cat:
def __init__(self, name):
self.name = name
def speak(self):
return self.name + ' says Meow!'
niko = Dog('Niko')
felix = Cat('Felix')
print(niko.speak())
print(felix.speak())
# 定义一个方法
def pet_speak(pet):
print(pet.speak())
# 定义一个基类Animal
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError('Subclass must implement abstract method')
class Dog(Animal):
def speak(self):
return self.name + ' says Woof'
class Cat(Animal):
def speak(self):
return self.name + ' says Meow!'
fido = Dog('Fido')
isis = Cat('Isis')
print(fido.speak())
print(isis.speak())
1.2.3、重置内置函数
- 比如__str__ 重写tostring方法
- 重写len() 方法
- 重写del() 删除方法
# 特殊方法, 自带方法,可以重写
class Book:
def __init__(self, title, author, pages):
print('A book is created')
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title: %s, author: %s, pages: %s" %(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print("A book is destroyed")
book = Book("Python Rocks!", "Jose Portilla", 159)
print(book)
print(len(book))
del book
2、错误和异常捕获
我们需要异常信息提示整个系统完整性
2.1、语法
"""
try:
捕获业务逻辑
except ExceptionI:
如果是异常ExceptionI 执行如下block块
except ExceptionII:
如果是异常ExceptionII,执行如下block块
else:
如果没有异常执行如下代码块
finally:
无论是否发现异常都会执行
"""
# 没有异常,它有写权限
try:
f = open('testfile','w')
f.write('Test write this')
except IOError:
print("Error: Could not find file or read data")
else:
print("Content written successfully")
f.close()
# 读权限
try:
f = open("testfile", 'r')
f.write("Test write this")
except IOError:
print("Error: Could not find file or read data")
else:
print("Content written successfully")
f.close()
2.2、finally 模块
- 语法
"""
try:
代码块
finally:
这段代码什么时候都会执行
"""
try:
f = open("testfile", "w")
f.write("Test write statement")
f.close()
finally:
print("Always execute finally code blocks")
# 直到输入正确的int的值
def askint():
while True:
try:
val = int(input("Please enter an integer: "))
except:
print("Looks like you did not enter an integer!")
continue
else:
print("Yep that's an integer")
print(val)
break
finally:
print("Finally, I executed!")
总结
- Class 是一切对象的模板
- 学习继承和实现定义:子类名(父类名), 例如 class Cat(Animal) Cat 继承Animal的类
- xxx 一般为内置的方法,例如__init__是构造函数的初始化方法
- 学习异常捕获try语法 except方法