shiniei
shiniei
发布于 2025-06-14 / 2 阅读
0
0

10.类

原理

当我们创建实例并运行的过程中,程序将自动执行__init__方法。而__init__方法中self形参的作用就在于把实例自身自动传到了self里面,同时我们把位置实参的值传给了__init__方法的形参name中,接着我们将形参name的值赋予给了self.name,这时也就相当于我们给实例创建了name属性,所以我们能在类外查看a.name的值(例如:print(a.name))
上面的大致流程也能说明为什么一定要在方法内加入形参self,因为编写py的认为你创建类一定会创建各种属性或者方法,所以得必须有self,否则实例将无法在类外使用这些属性或者方法

创建类

class Greet:
    '''打招呼'''
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print(f"hello,{self.name}")

创建实例/对象

a = Greet('Mot')

访问属性

print(a.name) # Mot

使用方法

a.say_hello() # hello,Mot

继承

super().__init__() 是 把子类实例本身(self)传给父类的 __init__ 方法, 所以父类就能在这个“子类实例”上添加属性(比如 self.name = ...), 最终这些属性就属于子类实例了,跟上面的原理类似.

class Two_dimensional:
    '''二次元角色'''
    def __init__(self, name, age, height):
        '''初始化'''
        self.name = name
        self.age = age
        self.height = height
    def describe_character(self):
        print(f'{self.name} is {self.age} years old and {self.height} cm tall.')

role = Two_dimensional('高木', 13, 150)
role.describe_character()
# 高木 is 13 years old and 150 cm tall.

class Arm:
    def __init__(self, arm_name):
        self.arm_name = arm_name
    def describe_arm(self):
        print(f'Her weapon name is {self.arm_name}.')

class Moe_enthusiast(Two_dimensional):
    '''萌系角色'''
    def __init__(self, name, age, height, moe_level, arm_name, likeability = 100, ):
        '''初始化父类属性 和 萌系角色特有属性'''
        super().__init__(name, age, height)
        self.moe_level = moe_level
        self.likeability = likeability
        self.arm_name = arm_name
        self.arm = Arm(self.arm_name) # 创建实例做属性

    def describe_character(self):
        '''调用父类方法 和 补充新信息'''
        super().describe_character()
        print(f'Her moe level is {self.moe_level}%')
    def likeability_text(self):
        '''喜爱程度'''
        print(f"Your affection for her is at {self.likeability}%.")

moe_role = Moe_enthusiast('宇泽玲纱', 15, 153, 100, 'Shooting ☆  Star', 99)
moe_role.describe_character()
# 宇泽玲纱 is 15 years old and 153 cm tall.
# Her moe level is 100%
moe_role.likeability_text()
# Your affection for her is at 99%.
moe_role.arm.describe_arm()
# Her weapon name is Shooting ☆  Star.

导入类

与导入函数方法是一样的,故不多赘述。

Py标准库

Py标准库是py在安装时就已经自带的模块
可以到 Python 3 Module of the Week 了解py标准库

>>> from random import randint
>>> randint(1,6) # 含两端
1
>>> randint(1,6)
1
>>> randint(1,6)
3
>>> randint(1,6)
1
>>> randint(1,6)
4
>>> randint(1,6)
4
>>> randint(1,6)
3
>>> randint(1,6)
6
>>> randint(1,6)
5
>>> from random import choice
>>> role = ['宇泽玲纱','小鸟游星野','可莉','纳西妲']
>>> first_up = choice(role) # 赋值会固定抽取结果
>>> first_up
'小鸟游星野'
>>> choice(role)
'可莉'
>>> choice(role)
'小鸟游星野'
>>> choice(role)
'宇泽玲纱'
>>> choice(role)
'可莉'
>>> choice(role)
'可莉'
>>> choice(role)
'纳西妲'

评论