面向对象基础(以python语言为例)

1、定义一个类;实例化类的对象;调用类中的方法

python 复制代码
#定义一个类
class Student:
    #类方法(即函数)
    def study(self,course_name):
        print(f'学生正在学习{course_name}')

    def play(self):
        print("xx学生正在玩游戏")

#实例化,stu1为类的对象
stu1=Student()
stu2=Student()

#调用类中的方法
Student().play()
stu1.study('hahhjaakjij')

2、创建属性,并在实例化时传入

python 复制代码
class Student:
    #初始化方法,创建属性
    def __init__(self,name,age):
      self.name=name
      self.age=age
    #
    def study(self,course_name):
        print(f'{self.name}正在学习{course_name}')

    def play(self):
        print(f'{self.name}正在玩游戏')

#实例化
stu1=Student('古成',18)
stu1.study('python')

3、访问权限

python 复制代码
class Student:
    def __init__(self,name,age):
      #创建私有属性
      self.__name=name
      self.__age = age
    def study(self,course_name):
        print(f'{self.__name}正在学习{course_name}')


stu =Student('kong',23)
stu.study('python')
print(stu.name)

4、继承

简单的来说就是将一个类Animal作为参数传入另一个类Dog的括号中

继承具有传递性。

python 复制代码
class Animal:
    def run(self):
        print("run")
    def eat(self):
        print("eat")

class Dog(Animal):
    def bark(self):
        print('bark')

class hashiqi(Dog):
    def play(self):
        print('hashiqi')

class Cat(Animal):
    def catch(self):
        print('scrach')

dog1=hashiqi()
dog1.run()
dog1.bark()
python 复制代码
#-*- codeing =utf-8 -*-
#Time:2023/11/11 21:48
#@Email: 2969234041@qq.com
#@Author:路遥知远
#@File:继承.py
#@Software:PyCharm
#动物类
class Animal:
    def run(self):
        print("run")
    def eat(self):
        print("eat")
#狗类
class Dog(Animal):
    def bark(self):
        print('bark')
#哈士奇
class hashiqi(Dog):
    def play(self):
        print('hashiqi')
    #在子类中重写父类的方法,最终会执行子类中的
    def bark(self):
        print("牛呀")
#猫类
class Cat(Animal):
    def catch(self):
        print('scrach')

dog1=hashiqi()
dog1.run()
dog1.bark()

5、重写

python 复制代码
#动物类
class Animal:
    def run(self):
        print("run")
    def eat(self):
        print("eat")
#狗类,继承动物类
class Dog(Animal):
    #自有方法
    def bark(self):
        print('bark')
#哈士奇,继承狗类
class hashiqi(Dog):
    def play(self):
        print('hashiqi')
    #在子类中重写父类的方法,最终会执行子类中的
    def bark(self):
        print("牛呀")

        super().bark()#调用父类中的方法
        print("测试")


dog1=hashiqi()
dog1.bark()

6、多态(不同子类调用相同父类产生不同结果)

相关推荐
用户8356290780513 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon4 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly4 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程4 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly6 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风13 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风13 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python