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

相关推荐
Tech Synapse4 分钟前
电商商品推荐系统实战:基于TensorFlow Recommenders构建智能推荐引擎
人工智能·python·tensorflow
聿小翼7 分钟前
selenium-wire 与 googletrans 的爱恨情仇
python
咖啡调调。9 分钟前
模板引擎语法-算术运算
python·django·sqlite
CodeCraft Studio10 分钟前
Excel处理控件Spire.XLS系列教程:Java设置Excel活动工作表或活动单元格
java·python·excel
Doker 多克10 分钟前
Python-Django系列—部件
开发语言·python
Linux运维老纪12 分钟前
Python文件操作及数据库交互(Python File Manipulation and Database Interaction)
linux·服务器·数据库·python·云计算·运维开发
Bruce_Liuxiaowei18 分钟前
MCP Python SDK构建的**SQLite浏览器**的完整操作指南
数据库·python·sqlite
q_q王19 分钟前
实时数字人——DH_LIVE
python·大模型·数字人·实时
江沉晚呤时26 分钟前
深入解析 ASP.NET Core 中的 ResourceFilter
开发语言·c#·.net·lucene
子燕若水27 分钟前
解释PyTorch中的广播机制
人工智能·pytorch·python