Python中的类(Class)的两种情况下的构造和实例化——无类属性时和有类属性时具体程序举例

Python中的类(Class)的两种情况下的构造和实例化——无类属性时和有类属性时具体程序举例

一、类的基本概念和特性

1.1 类的基本概念

在Python中,类(Class)是面向对象编程的核心概念,它是创建对象的蓝图或模板。类定义了对象的属性和方法,通过类可以创建多个具有相同结构和行为的对象实例。

1.2 类的三大特性

封装(Encapsulation):将数据和方法包装在类中,隐藏实现细节。
继承(Inheritance):子类可以继承父类的属性和方法 。
多态(Polymorphism):不同类的对象对同一消息做出不同响应

二、类的语法和说明

2.1 基本语法

class ClassName:
    """类的文档字符串"""
    
    def __init__(self, parameters0):      
        """构造方法,初始化对象属性"""
        self.attribute0 = parameters0
    
    def method1(self, parameters1):
        """实例方法"""
        # 方法体

2.2 使用说明

‘__init__’ 是 Python 的构造函数,在创建对象时自动调用。
self 代表类的实例本身。

三、无类属性情况下的类构造举例

3.1 实例属性无默认值的类构造举例

例子1:
构造一个含有年月日星期信息的类,它的实例属性无默认值。

(1) 构造类

class Myclass1():
    def __init__(self,Year,Month,Day,DW):
        """构造方法,初始化对象属性"""
        self.Year =Year;
        self.Month = Month;
        self.Day = Day;
        self.DW = DW;
    def M1(self):
        print("This year is",self.Year)
    def M2(self):
        print("This month is",self.Month)
    def M3(self):
        print("This day is",self.Day)
    def M4(self):
        print("This day of the week is",self.DW)

(2) 类的实例化

MC1=Myclass1(2025,6,23,'Monday')
## 调用类中的方法,
#注意:不能写成MC.M1,否则无法进行打印输出。
MC1.M1()      
MC1.M2()
MC1.M3()
MC1.M4()

运行结果:

This year is 2025
This month is 6
This day is 23
This day of the week is Monday

3.2 实例属性有默认值的类构造举例

例子1:
构造一个含有年月日星期信息的类,其实例属性默认值Year有默认值2024,Month有默认值5,Day有默认值8,DW有默认值’Wednesday’

(1) 构造类

class Myclass2():
      def __init__(self,Year=2024,Month=5,Day=8,DW='Wednesday'):   #Year有默认值2024,Month有默认值5,Day有默认值8,DW有默认值'Wednesday'
        """构造方法,初始化对象属性"""
        self.Year =Year;
        self.Month = Month;
        self.Day = Day;
        self.DW = DW;
      def F1(self):
        print("This year is",self.Year)
      def F2(self):
        print("This month is",self.Month)
      def F3(self):
        print("This day is",self.Day)
      def F4(self):
        print("This day of the week is",self.DW)

(2) 类的实例化

MC2=Myclass2(Year=2027)
## 调用类中的方法,
#注意:不能写成MC.M1,否则无法进行打印输出。
MC2.F1()      
MC2.F2()
MC2.F3()
MC2.F4()

运行结果:

This year is 2027
This month is 5
This day is 8
This day of the week is Wednesday

例子2:
构造一个包含名字和年龄的类,实例化的属性中age属性的默认值为18.

# 1.构造Person类
class Person:
    def __init__(self, name, age=18):  # age 有默认值 18
        self.name = name  # 初始化 name
        self.age = age    # 初始化 age

# 2.类的实例化
p1 = Person("Xiaohong")      # age 使用默认值 18
p2 = Person("Xiaoming", 25)    # age 显式设置为 25

print(p1.name, p1.age)    # 输出: Xiaohong 18
print(p2.name, p2.age)    # 输出: Xiaoming 25

运行结果:

Xiaohong 18
Xiaoming 25

例子3:
构造一个个人存取款过程的类。并记录存取的动态过程。实例属性中的 initial_balance的默认值为0,实例属性中的transactions默认初始值为空列表。实例属性中的amount无默认值。

(1)构造类

class BankAccount:
    def __init__(self, owner, initial_balance=0):
        self.owner = owner
        self.balance = initial_balance      # 记录余额
        self.transactions = []  # 初始化为空列表  ,用于记录交易过程

    def deposit(self, amount):      #存款操作
        self.balance += amount
        self.transactions.append(f"Deposit: +{amount}")

    def withdraw(self, amount):    #取款操作
        if amount <= self.balance:
            self.balance -= amount
            self.transactions.append(f"Withdraw: -{amount}")
        else:
            print("Insufficient funds!")     #提示余额不足

transactions 初始化为空列表,后续动态更新。
deposit() 和 withdraw() 是实例方法,用于修改对象状态。
(2)实例化类

account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200)
account.deposit(6500)

print(account.owner)            # Alice
print(account.balance)          # 7800
print(account.transactions)     # ['Deposit: +500', 'Withdraw: -200', 'Deposit: +6500']
account.withdraw(20000)         #Insufficient funds!

运行结果:

Alice
7800
['Deposit: +500', 'Withdraw: -200', 'Deposit: +6500']
Insufficient funds!

四、有类属性情况下的类构造举例

4.1 类属性有默认值+实例属性有默认值情况下构造类

(1) 构造类

# 1.构造类Car
class Car:
    wheels = 4  # 类属性(所有实例共享),设置类属性的默认值为4.

    def __init__(self, brand='Ferrari', color="red"):  # 设置实例属性中的brand的默认值为'Ferrari',实例属性中属性color的默认值为'red'
        self.brand = brand  # 实例属性
        self.color = color  # 实例属性

wheels 是类属性,所有 Car 实例共享。
brand 和 color 是实例属性,每个对象可以有不同的值。
(2) 类的实例化

# 2.实例化类Car
car1=Car()
car2 = Car("Tesla")          # color 默认 "red"
car3 = Car("BMW", "blue")    # color 显式设置为 "blue"

print(car1.brand, car1.color, car1.wheels)  # Ferrari red 4
print(car2.brand, car2.color, car2.wheels)  # Tesla red 4
print(car3.brand, car3.color, car3.wheels)  # BMW blue 4

运行结果:

Ferrari red 4
Tesla red 4
BMW blue 4

4.2 类属性无默认值+实例属性无默认值情况下构造类

例子:构造一个机器狗Robotic_dog的类,该类类属性和实例属性都无默认值,构造后并实例化。

# 1.构造类
class Robotic_dog:
    def __init__(self,name,state,color,species):
        self.name=name
        self.state=state
        self.color=color
        self.species=species
    def command(self,x):
        if x==self.name:
            self.bark(2)
        elif x=='sit':
            self.state='sit'
        else:
            self.state='wag tail'
    def bark(self,freq):
        for i in range(freq):
            print('['+self.name+']:Woof!')
# 2.类的实例化
            
bello=Robotic_dog(name='bello',state='sit',color='golden',species='Golden Retriever')
alice=Robotic_dog(name='alice',state='sleeping',color='white',species='Golden Retriever')
print(bello.color)   #打印为:golden
print(alice.color)   #打印为:white

bello.bark(1)
alice.bark(1)

bello.command('sit')
print('[bello]:'+bello.state)
bello.command('nono')
print('[bello]:'+bello.state)

alice.command('alice')
bello.command('bello')

print(bello.species)
bello.species='Teddy'
print(len(bello.species)==len(alice.species))

运行结果:

golden
white
[bello]:Woof!
[alice]:Woof!
[bello]:sit
[bello]:wag tail
[alice]:Woof!
[alice]:Woof!
[bello]:Woof!
[bello]:Woof!
Golden Retriever
False

五、总结

本文通过分两种情况(无类属性时和有类属性时)对类的构建和实例化进行了多个举例说明其用法,以加深对类的用法的认识和熟练使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值