Python的面向对象编程详解

嵌入式技术

1330人已加入

描述

一般编程可分为面向过程编程,和面向对象编程。Python的面向对象编程,与Java的面向对象很像。之所以需要面向对象编程,是为了更好地实现封装、继承、多态。

为了更加清晰地介绍Python的面向对象编程,以简单的代码作为案例,在案例中阐释Python的面向对象编程。

实验环境:Linux/Windows+Python3

1、定义类对象

# 类以关键字class开头
# 类名首字母都大写
class ClassName:
    # 构造函数,定义实例的属性
    # 构造函数的名称固定,后面可以跟任意个数参数,但第一个参数是默认的self
    def __init__(self, name, age):
        self.name = name
        self.age = age


# 创建实例对象,__init__将被调用
person = ClassName("name", 100)
# 获取对象的值
print(person.name)

执行该程序,将会打印

面向对象编程

2、定义类函数

# 类以关键字class开头
# 类名首字母都大写
class ClassName:
    # 构造函数,定义实例的属性
    # 构造函数的名称固定,后面可以跟任意个数参数,但第一个参数是默认的self
    def __init__(self, name, age):
        self.name = name
        self.age = age


    # 与普通函数定义类似,但第一个参数默认为self
    def functionName(self, age):
        print(self.name + ":", age)
        print(self.name + ":", self.age)


# 创建实例对象,__init__将被调用
person = ClassName("name", 100)
# 获取对象的值
print(person.name)
# 调用类函数
person.functionName(10)

执行该程序,将会打印

面向对象编程

3、继承父类

# 子类继承父类,后面加一个圆括号,里面放父类名称
class Student(ClassName):
    # 子类也需要构造方法
    def __init__(self, name, age, claRoom):
        # 继承父类的构造方法
        super().__init__(name, age)
        self.claRoom = claRoom


    def read(self, book):
        print("book name is ", book)


# 创建一个子类对象
student = Student("zhangsan", 20, 201)
# 获取子类的名称
print(student.name)
# 利用父类方法打印信息
student.functionName(30)
# 打印子类独有的信息
student.read("The C Programming")

执行该程序,将会打印

面向对象编程

4、多态

class Teacher(ClassName):
    # 子类也需要构造方法
    def __init__(self, name, age, claRoom):
        # 继承父类的构造方法
        super().__init__(name, age)
        self.claRoom = claRoom
    # 定义的方法名称与Student相同,但是功能不同
    def read(self, book):
        print("The reference book is ", book)


teacher = Teacher("lisi", 40, "T301")
print(teacher.age)
teacher.functionName(35)
teacher.read("The C Programming")

程序打印

面向对象编程

虽然都调用了read方法,但是两者实例对象不同,所执行的功能不同,这就是多态的妙处。

案例代码没有给出非常详细的解释,刨除了很多语法细节,可以作为一个快速掌握Python面向对象编程的笔记查阅。

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分