Python中class的用法


前言

Python中有很内置数据类型,数值类型int float complex,序列类型str list tuple range,集合类型set frozenset,映射类型dict,布尔类型bool,二进制类型bytes,bytearray。需要使用时,他们都可以去创建实例对象。
内置数据类型可直接使用,隐式创建,不用关键字int,str等

  • int:print(type(10)) 输出<class 'int'>
  • float print(type(10.007)) 输出<class 'float'>
  • complex print(type(4 + 5j)) 输出<class 'complex'>
  • str print(type('10')) 输出<class 'str'>
  • list tuple print(type([1, 3, '1', 4])) 输出<class 'list'>print(type((1, 3, '1', 4)))输出<class 'tuple'>;对应可变、不可变序列
  • range print(type(range(10))) 输出<class 'range'>,range是内置函数,返回一个可迭代对象
  • set frozenset print(type({1, 2, 3, 3, 4})) 输出<class ‘set’>;对应可变、不可变集合;集合无序,无索引,不能切片。
  • dict print(type({1: 'rat', 2: 'bat', 3: 'bird', 4: 'feather', 5: 'leather'})) 输出<class 'dict'>;键值对形式。
  • bytes print(type(b'\x01\x02\x03\x04'))输出<class 'bytes'>

同时,也可使用关键字创建实例,或实现类型转换。
在这里插入图片描述


一、类的定义

在Python中,类(Class)是一种用户定义的数据类型,它允许你创建具有相同属性和方法的对象(Object)。类是对象的蓝图或模板,而对象则是根据这个蓝图创建的实例。

class Dog:  
    # 类变量(静态变量),属于类本身,不属于类的任何实例  
    species = "Canis lupus familiaris"  
  
    # 初始化方法,当创建类的新实例时自动调用  
    def __init__(self, name, age):  
        # 实例变量(成员变量),属于类的每个实例  
        self.name = name  
        self.age = age  
  
    # 实例方法,属于类的实例  
    def bark(self):  
        print(f"{self.name} says Woof!")  
  
    # 类方法,通过装饰器@classmethod定义,属于类本身,但可以通过类实例访问  
    @classmethod  
    def class_method(cls):  
        print(f"The species of {cls.__name__} is {cls.species}")  
  
    # 静态方法,通过装饰器@staticmethod定义,不属于类也不属于类的实例,只是和类关联在一起  
    @staticmethod  
    def static_method():  
        print("This is a static method.")  
  
# 创建一个Dog类的实例  
my_dog = Dog("Buddy", 3)  
  
# 访问实例变量  
print(my_dog.name)  # 输出: Buddy  
print(my_dog.age)   # 输出: 3  
  
# 调用实例方法  
my_dog.bark()  # 输出: Buddy says Woof!  
  
# 调用类方法  
Dog.class_method()  # 输出: The species of Dog is Canis lupus familiaris  
my_dog.class_method()  # 同样可以通过实例调用类方法,但不建议这样做,因为这可能使代码更难以理解  
  
# 调用静态方法  
Dog.static_method()  # 输出: This is a static method.  
my_dog.static_method()  # 也可以通过实例调用静态方法,但同样不建议这样做

二、类的应用场景

1.数据建模-数据抽象和封装

类可以将数据(属性)和操作数据的方法(函数)封装在一起,形成一个独立的单元。这种封装隐藏了对象的内部细节,只提供公共的接口供外部使用,从而实现了数据抽象:长方形

class Rectangle:  
    def __init__(self, width, height):  
        self.width = width  
        self.height = height  

    def area(self):  
        return self.width * self.height  

# 创建一个Rectangle对象  
rect = Rectangle(10, 5)  
print(rect.area())  # 输出:50

2.创建对象实例,代码重用和多态

类是对象的蓝图或模板,你可以使用类来创建(实例化)多个具有相同属性和方法的对象。每个对象都是类的一个实例,并且具有自己的状态(属性值)。

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

# 创建两个Dog对象实例  
dog1 = Dog("Buddy", "Labrador")  
dog2 = Dog("Max", "Poodle")  
print(dog1.name)  # 输出:Buddy  
print(dog2.breed)  # 输出:Poodle

代码重用:通过继承(Inheritance),子类可以重用父类的属性和方法,从而避免了代码的重复编写。这有助于减少代码量,提高代码的可维护性。
实现多态性:多态性允许你使用相同的接口(方法名)来处理不同类型的对象。在Python中,这通常通过定义接口(如使用abc模块定义的抽象基类)或约定来实现。多态性使得代码更加灵活和可扩展。

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

    def speak(self):
        pass  # 抽象方法,具体实现在子类中

    def getLeatherColor(self):
        pass  # 抽象方法,具体实现在子类中


class Dog(Animal):
    def speak(self):
        return "Woof!"

    def getLeatherColor(self):
        return 'a white dog'


class Cat(Animal):
    def speak(self):
        return "Tiger!"

    def getLeatherColor(self):
        return 'an orange cat'


d = Dog("Fido")
c = Cat("Anne")
print(d.name)  # 初始化函数-重用,继承。输出:Fido
print(d.speak())  # 输出:Woof! 多态
print(d.getLeatherColor())  # 输出:'a white dog' 多态

print(c.name)  # 输出:Anne! 多态
print(c.speak())  # 输出:Tiger! 多态
print(c.getLeatherColor())  # 输出:'an orange cat'

3.组织代码管理封装

类提供了一种将相关的代码组织在一起的方式。通过将相关的属性和方法封装在类中,你可以更容易地理解和维护代码。此外,类还可以用于创建模块和包,进一步组织和管理代码。

# 文件名:math_operations.py  
class MathUtils:  
    @staticmethod  
    def add(a, b):  
        return a + b  

    @staticmethod  
    def multiply(a, b):  
        return a * b  

# 在其他文件中  
from math_operations import MathUtils  
print(MathUtils.add(5, 3))  # 输出:8

注:静态方法,通过装饰器@staticmethod定义,不属于类也不属于类的实例,只是和类关联在一起 。它们就像普通的函数一样,但可以在类的命名空间下调用。

3.实现设计模式

设计模式是解决常见软件设计问题的最佳实践。类是实现这些设计模式的基础。例如,你可以使用类来实现单例模式、工厂模式、观察者模式等。

以单例模式(如果此类还没有实例,就生成一个实例,如果一创建过,则返回那一个实例。)为例:

class Singleton:  
    _instance = None  

    def __new__(cls, *args, **kwargs):  
        if cls._instance is None:  
            cls._instance = super().__new__(cls)  
        return cls._instance  

a = Singleton()  
b = Singleton()  
print(a is b)  # 输出:True,证明a和b是同一个实例
print('a-id:', id(a))  # 输出id值
print('b-id:', id(b))  # 输出id值同上,说明是同一个内存上的同一个东西。

在这里插入图片描述
注: 输出id值一样,说明是同一个内存上的同一个东西。

4.数据验证和封装逻辑

在类的内部,你可以编写用于验证数据有效性的代码,并封装与数据相关的逻辑。这有助于确保数据的完整性和正确性,并减少错误的可能性。

class BankAccount:  
    def __init__(self, balance):  
        if balance < 0:  
            raise ValueError("Balance cannot be negative.")  
        self._balance = balance  # 余额

    def deposit(self, amount):  # 存款:验证数据,封装逻辑
        if amount < 0:  
            raise ValueError("Deposit amount cannot be negative.")  
        self._balance += amount  #金额

    def withdraw(self, amount):  # 取款::验证数据,封装逻辑
        if amount > self._balance or amount < 0:   
            raise ValueError("Insufficient funds or withdrawal amount cannot be negative.")  # 余额不足
        self._balance -= amount  

    def get_balance(self):   # 查询余额
        return self._balance

5.模拟现实世界中的事物

类可以用于模拟现实世界中的事物,如人、动物、汽车、房屋等。通过定义这些事物的属性和方法,你可以使用代码来模拟它们的行为和交互。

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

    def introduce(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

    def greet(self, other_person):
        print(f"{self.name} says hello to {other_person.name}!")


class Man(Person):
    def __init__(self, name, age):
        super().__init__(name, age, "Male")

    def goto_date(self, woman):
        if isinstance(woman, Woman):  # 类型限定
            print(f"{self.name} go to date {woman.name}!")
        else:
            print(f"{self.name} can only go to date a Woman, not a {type(woman).__name__}!")


class Woman(Person):
    def __init__(self, name, age):
        super().__init__(name, age, "Female")

    def smile(self, man):
        if isinstance(man, Man):
            print(f"{self.name} smiles at {man.name}!")
        else:
            print(f"{self.name} can only smile at a Man, not a {type(man).__name__}!")

        # 创建对象并调用方法


john = Man("John", 30)
alice = Woman("Alice", 25)

john.introduce()
alice.introduce()

# 数据交互:问候
john.greet(alice)
alice.greet(john)

# 数据交互:特定于男人和女人的行为-约会
john.goto_date(alice)
alice.smile(john)

# 尝试不合适的交互(只是为了演示)
john.goto_date(john)  # 这应该输出一个错误消息

在这里插入图片描述
在这个示例中,Person类有一个greet方法,它允许任何Person对象与其他Person对象打招呼。Man类添加了一个goto_date方法,专门用于与Woman对象约会。类似地,Woman类添加了一个smile方法,专门用于对Man对象微笑。添加了一些类型检查,以确保flirt和smile方法只与预期的对象类型一起使用。如果传递了错误的对象类型,则会打印出错误消息。

使用类,可简化复杂系统:对于大型和复杂的系统,使用类可以帮助你简化和组织代码。通过将系统的不同部分划分为不同的类,你可以更容易地理解和维护系统的各个组件。

6.提供公共接口

类提供了一个公共的接口,使得外部代码可以通过该接口与类的实例进行交互。这有助于隐藏类的内部实现细节,并使得代码更加模块化和可维护。

# 公共接口模块
class PersonInterface:
    @staticmethod
    def interact_with_person(person1, person2):
        person1.introduce()
        person2.introduce()
        person1.greet(person2)
        person2.greet(person1)

    # 使用示例

# Man,Woman接上一个示例
john = Man("John", 30)
alice = Woman("Alice", 25)

# 通过公共接口进行交互
PersonInterface.interact_with_person(john, alice)

7.支持面向对象的分析和设计

在软件开发过程中,面向对象的分析和设计(OOAD)是一种常用的方法。类作为面向对象编程的核心概念之一,支持这种分析和设计方法,并有助于创建出更加健壮、可维护和可扩展的软件系统。
应用示例:python的GUI之计算器


Tips
__new__方法是一个特殊的静态方法,用于实例化对象。通常不需要直接调用__new__方法,Python会自动调用它来分配内存空间并返回一个新对象。特殊情况下,使用__new__方法来限制只能创建特定数量的实例;需要重写__new__方法来控制对象的创建过程。

  • 15
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏常青

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值