编程学习网 > 编程语言 > Python > python的Class类和类的继承教程!
2023
11-11

python的Class类和类的继承教程!

Python 中的类是一种封装数据和行为的机制。通过类,可以将相关的数据和函数封装在一起,形成一个独立的逻辑单元。创建一个类就相当于创建了一种新的数据类型,类的实例对象就相当于数据类型的实例化。

在 Python 中,使用 class 关键字来定义一个类,类名通常以大写字母开头。类中可以定义属性和方法。属性用于描述类的特征,方法用于描述类的行为。类中的方法可以访问和修改类的属性,从而实现对类的状态和行为的控制。
类中的属性包括实例属性和类属性。实例属性是指每个对象都会拥有一份的属性,而类属性是指与类本身关联的属性。实例属性可以通过 self 关键字来创建和访问,类属性可以通过在类中直接定义和访问。
类中的方法分为普通方法、类方法和静态方法。普通方法是类中最常见的方法,它可以访问和修改实例属性,同时也可以调用其他方法和函数。类方法是归属于类的一种方法,其第一个参数是类本身,类方法可以访问和修改类属性,但不能访问实例属性。静态方法是不归属于任何实例或类的方法,它可以被类和实例调用,但不能访问实例属性和类属性。
除了上述概念,类还支持多重继承(即一个类可以继承多个父类),以及方法重写、方法重载等高级特性。
01、类对象的使用
下面以一个实际场景的例子介绍 Python 类的用法。
假设我们要编写一个程序来管理图书馆的图书信息。每一本书都有书名、作者、出版社、出版时间等属性,同时也具有借阅、归还等方法。这时候,可以定义一个 Book 类来描述每一本书的属性和行为,具体实现如下:
class Book:
    def __init__(self, title, author, publisher, publish_date):
        self.title = title
        self.author = author
        self.publisher = publisher
        self.publish_date = publish_date
        self.is_borrowed = False
    
    def borrow(self):
        if self.is_borrowed:
            print(f"{self.title} has been borrowed, please try later.")
        else:
            self.is_borrowed = True
            print(f"{self.title} has been borrowed successfully.")
    
    def return_book(self):
        if self.is_borrowed:
            self.is_borrowed = False
            print(f"{self.title} has been returned successfully.")
        else:
            print(f"{self.title} has not been borrowed.")
在上述代码中,我们定义了一个 Book 类,包含了该类的初始化函数__init__(),以及 borrow() 和 return_book() 等方法。其中,init() 方法用于初始化 Book 类的实例对象,在创建实例时传入所需的参数。borrow() 和 return_book() 方法分别用于借阅和归还书籍,用于改变 is_borrowed 属性的值。
接下来,我们可以实例化一个 Book 对象,并调用它的 borrow() 和 return_book() 方法:
book1 = Book("The Alchemist", "Paulo Coelho", "HarperCollins", "1988-01-01")
book1.borrow()   # The Alchemist has been borrowed successfully.
book1.return_book()   # The Alchemist has been returned successfully.
此外,还可以定义一个 Library 类来封装管理图书馆的操作。这个类可以包含添加书籍、删除书籍、查找书籍等方法,使用 Book 对象来存储每本书的信息。具体实现如下:
class Library:
    def __init__(self):
        self.books = []
    
    def add_book(self, book):
        self.books.append(book)
        print(f"{book.title} has been added to the library.")
    
    def remove_book(self, book):
        self.books.remove(book)
        print(f"{book.title} has been removed from the library.")
    
    def find_book(self, title):
        for book in self.books:
            if book.title == title:
                return book
        print(f"{title} is not found in the library.")
        return None
在上述代码中,我们定义了一个 Library 类,包含了该类的初始化函数__init__(),以及 add_book()、remove_book() 和 find_book() 等方法。其中,init() 方法用于初始化 Library 类的实例对象,add_book() 和 remove_book() 方法分别用于添加书籍和删除书籍,find_book() 方法用于查找书籍。
接下来,我们实例化一个 Library 对象,并向其中添加一些书籍:
python
lib = Library()
book1 = Book("The Alchemist", "Paulo Coelho", "HarperCollins", "1988-01-01")
book2 = Book("The Catcher in the Rye", "J.D. Salinger", "Little, Brown and Company", "1951-07-16")
lib.add_book(book1)   # The Alchemist has been added to the library.
lib.add_book(book2)   # The Catcher in the Rye has been added to the library.
    最后,我们可以通过查找书籍的方式来改变书籍的属性:‍
book = lib.find_book("The Alchemist")
if book:
    book.borrow()   # The Alchemist has been borrowed successfully.

book = lib.find_book("The Catcher in the Rye")
if book:
    book.borrow()   # The Catcher in the Rye has been borrowed successfully.

book = lib.find_book("The Alchemist")
if book:

    book.return_book()   # The Alchemist has been returned successfully.

综上所述,通过一个图书馆管理系统的例子,我们展示了 Python 类的用法,包括定义类、实例化对象、访问对象属性和方法。

02、类对象的继承

下面以一个人类(Human)的类为例,详细介绍Python类的用法和对象继承。
1. 基本概念
在Python中,类是一种自定义的数据类型。类中可以定义变量和方法,用来描述一类对象(各个对象共同的属性和行为)。
2. 定义类
在Python中,使用class关键字定义类,其基本语法格式如下:
class 类名(父类):
    属性1 = 初始值
    属性2 = 初始值
    ...
    方法1()
    方法2()
    ...
其中,父类可以省略不写,默认继承于object类。例如,我们定义一个人类:
class Human:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
    def say_hello(self):
        print(f'Hello, my name is {self.name}.')
    上述Human类有三个属性(name、age、gender)和一个方法(say_hello),其中__init__()方法为构造函数,当创建实例对象时会自动调用该方法。
3. 继承
在Python中,类与类之间可以进行继承,即一个类可以从另一个类中继承属性和方法。语法格式如下:
class 类名(父类):
    ...
    例如,我们定义一个学生类(Student),并继承于人类(Human):
class Student(Human):
    def __init__(self, name, age, gender, grade):
        super().__init__(name, age, gender)
        self.grade = grade
    def study(self):
        print(f'{self.name} is studying in grade {self.grade}.')
  上述Student类继承了Human类,即在Student类中可以访问Human类中定义的属性和方法。

4. 创建子类对象
    创建子类对象时,会自动调用父类的构造函数,例如:
lisi = Student('李四', 16, '男', 10)
      此时,lisi既拥有Student类中定义的属性和方法,也拥有Human类中定义的属性和方法,因为Student类继承了Human类。

print(lisi.gender)      # 访问Human类中的属性
lisi.say_hello()        # 调用Human类中的方法
lisi.study()            # 调用Student类中的方法
输出结果为:


Hello, my name is 李四.
李四 is studying in grade 10.

综上所述,Python中的类是一种自定义的数据类型,可用于描述一类对象。通过类可以创建对象,访问对象的属性和方法,还可以进行继承。

以上就是python的Class类和类的继承教程!的详细内容,想要了解更多Python教程欢迎持续关注编程学习网。

扫码二维码 获取免费视频学习资料

Python编程学习

查 看2022高级编程视频教程免费获取