学习笔记——面向对象

面向对象

优点:易维护、复用、扩展

万物皆可为对象 对象有属性和行为

创建对象实例:

对象=类()

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值