【深度学习】 Python 和 NumPy 系列教程(八):Python类

目录

一、前言

二、实验环境

三、Python类(Class)

1、初始化方法(__init__)

2、属性和实例变量

3、方法和实例方法

4、继承

5、多态

6、类变量和静态方法

7、魔术方法


一、前言

        Python是一种高级编程语言,由Guido van Rossum于1991年创建。它以简洁、易读的语法而闻名,并且具有强大的功能和广泛的应用领域。Python具有丰富的标准库和第三方库,可以用于开发各种类型的应用程序,包括Web开发、数据分析、人工智能、科学计算、自动化脚本等。

        Python本身是一种伟大的通用编程语言,在一些流行的库(numpy,scipy,matplotlib)的帮助下,成为了科学计算的强大环境。本系列将介绍Python编程语言和使用Python进行科学计算的方法,主要包含以下内容:

  • Python:基本数据类型、容器(列表、元组、集合、字典)、函数、类
  • Numpy:数组、数组索引、数据类型、数组数学、广播
  • Matplotlib:绘图,子图,图像
  • IPython:创建笔记本,典型工作流程

二、实验环境

        Python 3.7

        运行下述命令检查Python版本

 python --version 

三、Python类(Class)

1、初始化方法(__init__

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 25)
print(person.name)  # 输出: Alice
print(person.age)  # 输出: 25

        __init__方法用于初始化Person类的对象。通过self.name = nameself.age = age语句,将传递给构造函数的参数赋值给对象的属性。

2、属性和实例变量

class Circle:
    def __init__(self, radius):
        self.radius = radius

circle = Circle(5)
print(circle.radius)  # 输出: 5

        Circle类具有一个属性radius,并且在初始化方法中使用传递的参数对其进行赋值。通过circle.radius可以访问对象的属性。

3、方法和实例方法

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} is barking!")

dog = Dog("Buddy")
dog.bark()  # 输出: Buddy is barking!

        Dog类具有一个方法bark,通过self.name访问对象的属性,并输出相应的信息。

4、继承

class Animal:
    def __init__(self, name):
        self.name = name

    def eat(self):
        print(f"{self.name} is eating.")

class Dog(Animal):
    def bark(self):
        print("Woof!")

dog = Dog("Buddy")
dog.eat()  # 输出: Buddy is eating.
dog.bark()  # 输出: Woof!

        Dog类继承自Animal类,并且可以使用Animal类中定义的方法和属性。子类可以添加新的方法,如bark

5、多态

class Animal:
    def __init__(self, name):
        self.name = name

    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("Woof!")

class Cat(Animal):
    def make_sound(self):
        print("Meow!")

animals = [Dog("Buddy"), Cat("Whiskers")]

for animal in animals:
    animal.make_sound()

        Animal类具有一个make_sound方法,但是在子类中具有不同的实现方式。通过遍历animals列表,可以调用不同类的make_sound方法实现多态。

6、类变量和静态方法

class Circle:
    pi = 3.14159

    def __init__(self, radius):
        self.radius = radius

    @staticmethod
    def calculate_area(radius):
        return Circle.pi * radius ** 2

circle = Circle(5)
print(circle.calculate_area(5))  # 输出: 78.53975
print(Circle.calculate_area(5))  # 输出: 78.53975

       pi是一个类变量,被所有实例共享。calculate_area是一个静态方法,可以通过类名或实例来调用。

7、魔术方法

class Person:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f"Person: {self.name}"

person = Person("Alice")
print(person)  # 输出: Person: Alice

        __str__是一个魔术方法,用于返回对象的字符串表示。通过在类中定义__str__方法,可以自定义对象的字符串输出形式。

猜你喜欢

转载自blog.csdn.net/m0_63834988/article/details/132781910