面向对象
优点:易维护、复用、扩展
万物皆可为对象 对象有属性和行为
创建对象实例:
对象=类()
class 类的名称:
赋属性
def__init__(self,属性的名字1,属性的名字2):
类的构造方法
==def basketbal(self): print(f"{self.name} 会打篮球")==打f格式化输出,可以输出字符串和数字
创建实例
对象=类( )
print()
def study(self): 定义行为
对象.study
封装、继承、多态
封装
隐藏对象中一些不希望被外部访问的
self.__属性名称=属性名称 添加两个下划线
如self.__password=password
继承
子承父类
class 子类(父类名字):
def __init__(self,自己的属性):
self.属性名字=属性名字
def 特殊属性(self):
print()
多态
它可以用父类的对象,也可以用子类的对象
课上练习存档
importmath
classcir:
def__init__(self,R)
self.R=R
def S(self):
print(math.pi*self.R**2)
circle=cir(2)
circle.S()
import math
class Shape:
def __init__(self,name):
self.name = name
def s(self):
print()
def c(self):
print()
class Circle(Shape):
def __init__(self,r):
self.r = r
def s(self):
print(math.pi*self.r**2)
def c(self):
print(math.pi*2*self.r)
class Rectangle(Shape):
def __init__(self,width,height): #要记得def后面打空格
self.width=width
self.height=height
def s(self): #当子类和父类方法同名时,子类方法会覆盖父类的方法
print(self.width * self.height) #要记得缩进self才能发亮
def c(self):
print((self.width + self.height) * 2)
def shape_back(shape):
if isinstance(shape,Shape):
shape.s()
shape.c()
a=int(input())
b=int(input())
c=int(input())
circle=Circle(a)
shape_back(circle)
rectangle=Rectangle(b,c)
shape_back(rectangle)