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

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

#定义一个类
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、创建属性,并在实例化时传入

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、访问权限

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语言为例)_第1张图片

继承具有传递性。

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()
#-*- 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()

 面向对象基础(以python语言为例)_第2张图片

5、重写 

#动物类
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、多态(不同子类调用相同父类产生不同结果)

面向对象基础(以python语言为例)_第3张图片

你可能感兴趣的:(python(人工智能),python,开发语言)