面向对象基础(以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、多态(不同子类调用相同父类产生不同结果)

相关推荐
weixin_447195297 分钟前
【无标题】
pytorch·python
迅猛龙办公室9 分钟前
Python实现简单的人名对话
python
阿坨37 分钟前
firestart:一行命令启动你的日常应用和网页
python·pypi·cli·click
老歌老听老掉牙1 小时前
麻花钻切屑形态演变的力学机制与临界条件分析
python·算法·钻头
周杰偷奶茶1 小时前
【Java】数组的定义和使用(附管理系统实战案例)
java·开发语言
happylifetree1 小时前
Python18(补充):练习
python
橙子圆1232 小时前
JUC之集合类不安全
java·开发语言
阿里嘎多学长2 小时前
2026-09-29 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Bruce_Liuxiaowei2 小时前
网页版 DeepSeek “harness desktop“ WebGL 上下文创建失败排查实录
开发语言·javascript·webgl
weixin_416667962 小时前
银河麒麟V10看门狗试验-1
网络·chrome·python