diff --git a/tasks/task1/submit/.keep b/tasks/task1/submit/.keep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tasks/task1/submit/.keep @@ -0,0 +1 @@ + diff --git a/tasks/task1/submit/test1/note/artribute.py b/tasks/task1/submit/test1/note/artribute.py new file mode 100644 index 0000000..1a76820 --- /dev/null +++ b/tasks/task1/submit/test1/note/artribute.py @@ -0,0 +1,105 @@ +'''类属性''' +class Car: + # 类属性 + wheels = 4 + + def __init__(self, make, model): + self.make = make # 实例属性make + self.model = model # 实例属性model + + # 创建Car实例 +car1 = Car("Toyota", "Camry") +car2 = Car("Honda", "Civic") + +# 访问类属性 +print(car1.wheels) # 输出: 4 +print(car2.wheels) # 输出: 4 + +'''公有属性x''' +class Animal: + x=10 + def test(self): + print(Animal.x) + print(self.x) +class Dog(Animal): + def test2(self): + print(Dog.x) + print(Animal.x) +#测试代码 +animal1=Animal() +animal1.test()#10 10 +print(animal1.x) +dog1=Dog() +dog1.test2()#10 10 +print(dog1.x) + + +'''受保护的属性''' + +''' 属性访问器(Getter)和修改器(Setter)是用来访问和修改属性的特殊方法。使用它们可以在访问属性时进行额外的逻辑处理。''' +class Circle: + def __init__(self, radius): + self._radius = radius # 私有属性,约定使用下划线开头 + + # 属性访问器(Getter) + @property + def radius(self): + return self._radius + + # 属性修改器(Setter) + @radius.setter + def radius(self, value): + if value >= 0: + self._radius = value + else: + raise ValueError("半径不能为负数") + +# 创建Circle实例 +circle = Circle(5) + +# 使用属性访问器获取半径 +print(circle.radius) # 输出: 5 + +# 使用属性修改器设置半径 +circle.radius = 10 +print(circle.radius) # 输出: 10 + +# 尝试设置负数半径,将会引发ValueError +circle.radius = -1 +''' 在上述代码中,使用@property装饰器定义了一个名为radius的属性访问器,用于获取_radius的值。 +同时,使用@radius.setter装饰器定义了属性修改器,用于设置_radius的值。 +这样,我们可以像访问普通属性一样使用circle.radius来获取和设置_radius的值。 ''' + + + +#特殊的类属性 +'''特殊的类属性:对于所有的类,都有一组特殊的属性 + +_ _ name_ _ # 类的名字(字符串) +_ _ doc _ _ # 类的文档字符串 +_ _ bases _ _ # 类的所有父类组成的元组 +_ _ dict _ _ # 类的属性组成的字典 +_ _ module _ _ # 类所属的模块 +_ _ class _ _ # 类对象的类型 +''' +class object_example: + def __init__(self) -> None: + pass + +class person(object_example): + '''there is doc''' + tall = 180 + hobbies = [] + def __init__(self, name, age,weight): + self.name = name + self.age = age + self.weight = weight + def infoma(self): + print('%s is %s weights %s'%(self.name,self.age,self.weight)) + +print(person.__name__) # person +print(person.__doc__) # there is doc +print(person.__bases__) # (,) +print(person.__dir__) # +print(person.__module__) # __main__ +print(person.__class__) # \ No newline at end of file diff --git a/tasks/task1/submit/test1/note/decoraters.py b/tasks/task1/submit/test1/note/decoraters.py new file mode 100644 index 0000000..ea5d119 --- /dev/null +++ b/tasks/task1/submit/test1/note/decoraters.py @@ -0,0 +1,81 @@ +'''属性和方法的装饰器是Python中用于对属性和方法进行额外操作的特殊注解。 +装饰器能够简化代码、提高代码的复用性,并使代码更加优雅。''' + +#@property装饰器 +'''@property装饰器用于将一个方法转换为只读属性,使得我们可以像访问属性一样访问这个方法,而无需使用括号。''' + +'''在下述代码中,我们定义了一个Circle类, +其中area方法用于计算圆的面积, +@property装饰器将radius方法转换为只读属性。 +使用@property装饰器后,我们可以像访问属性一样访问circle.radius获取圆的半径。''' + +class Circle: + def __init__(self, radius): + self._radius = radius # 私有属性,约定使用下划线开头 + + # 属性访问器(Getter) + @property + def radius(self): + return self._radius + + # 计算圆的面积 + def area(self): + return 3.14159 * self._radius * self._radius + +# 创建Circle实例 +circle = Circle(5) + +# 使用属性访问器获取半径 +print(circle.radius) # 输出: 5 + +# 使用方法计算圆的面积 +print(circle.area()) # 输出: 78.53975 + +# 使用属性访问器获取面积(注意:这里不需要加括号) +print(circle.area) # 输出: > + +#@classmethod装饰器 +'''@classmethod装饰器用于定义类方法,类方法的第一个参数通常命名为cls,表示对类本身进行操作。''' + +'''在下述代码中,我们定义了一个MathUtils类, +其中的circle_area方法是一个类方法,用于计算圆的面积。 +在类方法内部,我们可以通过cls访问类的属性和方法。''' +class MathUtils: + PI = 3.1415926 + + # 类方法 + @classmethod + def circle_area(cls, radius): + return cls.PI * radius * radius + +# 调用类方法 +area = MathUtils.circle_area(5) +print(area) # 输出: 78.539815 + + #@staticmethod装饰器 +'''@staticmethod装饰器用于定义静态方法,静态方法与类和实例无关,通常用于执行与类相关的实用函数。''' +class StringUtils: + # 静态方法 + @staticmethod + def is_palindrome(s): + return s == s[::-1] + +# 调用静态方法 +result = StringUtils.is_palindrome("level") +print(result) # 输出: True + +'''Python支持类装饰器。类装饰器是包含 __call__ 方法的类,它接受一个函数作为参数,并返回一个新的函数。''' +class DecoratorClass: + def __init__(self, func): + self.func = func + + def __call__(self, *args, **kwargs): + # 在调用原始函数之前/之后执行的代码 + result = self.func(*args, **kwargs) + # 在调用原始函数之后执行的代码 + return result + + +@DecoratorClass +def my_function(): + pass \ No newline at end of file diff --git a/tasks/task1/submit/test1/note/inherit.py b/tasks/task1/submit/test1/note/inherit.py new file mode 100644 index 0000000..d47579b --- /dev/null +++ b/tasks/task1/submit/test1/note/inherit.py @@ -0,0 +1,189 @@ +#属性和方法的继承 +'''在Python中,子类可以继承父类的属性和方法。子类可以在继承的基础上进行扩展和修改,或者覆盖父类的方法。''' +class Animal: + def __init__(self, species): + self.species = species + + def make_sound(self): + return "吱吱" # 默认动物叫声 + +class Dog(Animal): + def __init__(self, name): + super().__init__("犬科")#调用父类的属性,并初始化为犬科 + self.name = name + # 重写make_sound方法 + def make_sound(self): + return "汪汪!我是" + self.name +# 创建Dog实例 +dog = Dog("小白") +# 调用继承的方法 +print(dog.species) # 输出: "犬科" +# 调用子类的方法(覆盖了父类的方法) +print(dog.make_sound()) # 输出: "汪汪!我是小白" + + +# 父类 +class Person: + def __init__(mysillyobject, firstname, lastname): + mysillyobject.name = firstname + mysillyobject.family = lastname + + def myfunc(abc): + print("Hello my name is " + abc.name) + +# 子类,继承 +class Student(Person): + def __init__(self, fname, year, lname):#添加 __init__() 函数 + super().__init__(fname, lname) # 调用父类的属性赋值方法,super() 函数,使子类自动从其父继承所有方法和属性 + self.graduationyear = year # 子类自己的属性 + + def welcome(self): + # 子类自己的方法 + print("Welcome", self.name, self.family, "to the class of", self.graduationyear) + +#创建student实例 +x = Student("Elon", 2019, "Musk") +x.welcome()#输出: Welcome Elon Musk to the class of 2019 + + +#扩展: 覆盖(or重写) /重载 (override/ reload) +'''如果在开发中,子类的方法中包含父类的方法,父类原本的方法是子类方法的一部分,就可以采用扩展的方式。 + +扩展的方式步骤: + + 1.在子类中重写父类的方法 + 2.在需要的位置使用 super().父类方法 来调用父类方法的执行 + 3.代码其他的位置针对子类的需求,编写子类特有的代码实现 + +第2点.关于super: + 在python中super是一个特殊的类,super()就是使用super类创建出来的对象 + 最常使用的场景就是,在重写父类方法时,让super().调用在父类中封装的方法''' +# 单继承, 子类对父类扩展:新增方法、重写方法、子类中使用super().调用父类方法 +class Animal(): + def eat(self): + print("吃") + + def run(self): + print("跑") + + def drink(self): + print("喝") + + def sleep(self): + print("睡") + + +class Dog(Animal): + + def bark(self): + print("汪汪叫") + + +class XiaoTianQuan(Dog): + + def fly(self): + print("会飞") + + def bark(self): + # 1. 针对子类特有的需求,编写代码 + print("天籁之音") + + # 2. 使用super(). 调用原本在父类中封装的方法 + super().bark() + + # 3. 增加其他子类的代码 + print("OKOK") + + +# 创建一个哮天犬对象 +xtq = XiaoTianQuan() + +xtq.bark() +xtq.drink() +xtq.sleep() + + + +'''覆盖(Override):指在继承中,父类的有些方法在子类中不适用,子类重新定义。 +注意: +若子类中被“覆盖”方法的参数类型不同,返回类型不一致,这不是覆盖,而是重载。覆盖要求参数类型必须一样,且返回类型必须兼容。总之,子类对象得保证能够执行父类的一切。 +不能降低覆盖方法的存取权限,如public变成private。 +若不希望父类的某个方法被子类覆盖,可以用final修饰该方法。甚至可以扩展到将类用final修饰,则其中所有的方法均不可覆盖,但不影响成员变量的赋值。 + +子类如何重写父类的方法? +前提: +规则一:重写方法不能比被重写方法限制有更严格的访问级别。 +(但是可以更广泛,比如父类方法是保护访问权限,子类的重写方法是public访问权限。) + +规则二:参数列表必须与被重写方法的相同。 +(需要注意的是如果子类方法的参数和父类对应的方法不一样,那就不是重写,而是重载) + +规则三:返回类型必须与被重写方法的返回类型相同。 + +规则四:重写方法不能抛出新的异常或者比被重写方法声明的检查异常更广的检查异常。但是可以抛出更少,更有限或者不抛出异常。 + +规则五:不能重写被标识为final的方法。 + +规则六:如果一个方法不能被继承,则不能重写它。比如父类的私有方法就不能被重写。 + +如果子类能够继承父类的某个方法, 那么子类就能够重写这个方法。 +''' + + +# 如果子类中重写了父类方法 +# 在使用子类对象调用方法时,会调用子类中重写的方法 +class XiaoTianQuan(Dog): + + def fly(self): + print("会飞") + + def bark(self): + print("OKOK") + + +class TuDog(Dog): + def fly(self): + pass + + def bark(self): + print("小土狗") + + +# 创建对象1 +xtq = XiaoTianQuan() +xtq.bark() +xtq.drink() +xtq.sleep() + +# 创建对象2 +tg = TuDog() +tg.bark() +tg.fly() + + +#多态 +'''多态就是“具有多种形态”,它指的是:即便不知道一个变量所引用的对象到底是什么类型,仍然可以通过这个变量的调用方法, +在运行过程中根据变量所引用对象的类型,动态决定调用哪个对象中的方法。 +当子类和父类存在相同的方法的时候,子类的方法会覆盖父类的方法,这样代码在运行时总会调用子类的方法,这就是多态。 +判断一个实例是不是某个对象,可以使用isinstance()函数,是则输出True,反之输出False。 +''' +print('---------------------多态------------------------') +class Animal: + def say(self): + print('Animal') +class Dog(Animal): + def say(self): + print('Dog') +class Cat(Animal): + def say(self): + print('Cat') +animal = Animal() +animal.say() +dog = Dog() +dog.say() +cat = Cat() +cat.say() +print('-------------------------isinstance()----------------------') +print(isinstance(dog, Dog))#True +print(isinstance(dog, Cat))#False +print(isinstance(dog, Animal))#True \ No newline at end of file diff --git a/tasks/task1/submit/test1/note/learn1.py b/tasks/task1/submit/test1/note/learn1.py new file mode 100644 index 0000000..7735fb4 --- /dev/null +++ b/tasks/task1/submit/test1/note/learn1.py @@ -0,0 +1,183 @@ +# class Money: +# age=11 +# num=666 +# pass +# one=Money() +# Money.count=1 +# print(Money.count) +# print(Money.__dict__) +# Money.age=22 +# print(Money.age) +# del Money.age +# one.__dict__={"sex":1} +# print(one.__dict__) +# print(one.count) +# class Person: +# ag=18 +# num=6 +# # __slots__={"age"} +# one=Person() +# two=Person() +# one.age=1 +# one.num=2 +# # one.age+=2 +# print(one.age) +# print(one.num) +# two.age+=1 +# print(two.age) +#方法(实例,类,静态) +# class Person: +# @classmethod +# def leifangdfa(cls): +# print("类方法") +# @staticmethod +# def jingtai(): +# print("静态方法") +# def eat(self,food): +# +# print("实例方法") +# print(self,food) +# p=Person() +# +# print(p.eat("土豆"),Person.jingtai(),Person.leifangdfa()) +# print(Person.eat('abc',"在吃饭")) +#类方法 +# class Person: +# age=10 +# def shili(self): +# print(self.age,self.num) +# @classmethod +# def leifangfa(cls): +# print("类方法",cls.age,cls.num) +# @staticmethod +# def jingtai(): +# print(Person.age) +# +# one=Person() +# one.num=1 +# one.age=5 +# # print(one.leifangfa(666)) +# one.shili() +# # one.leifangfa() +# one.jingtai() +#元类(type) +# class A: +# pass +# print(A.__class__) +# def run(self): +# print("函数") +# Dog=type('Dog',(),{'count':0,"run":run}) +# print(Dog.__dict__) +# d=Dog() +# d.run() +# class Dog(object): +# """This is a dog class as example""" +# +# animal_kind = 'dog' # 基本属性 +# animal_legs = 4 # 基本属性也建议写到初始化构造函数中去 +# +# def __init__(self, name, age, params): +# ''' This is initial funciton''' +# self.name = name +# self.age = age +# # 还可以定义各种其他的属性,作为实例初始化时候将传进来的参数进行赋值 +# self.__gender = 'male' # 两个下划线开头是私有内部属性,只能在类内访问 +# +# def __privateGender(self): +# """This is pravate method""" +# print('This dog gender is %s', self.__gender) +# +# +# def voice(self): +# """Dog will speak as wangwang """ +# print('WangWangWang') +# print(self.__privateGender(self)) +# +# +# def run(self): +# """runing with legs""" +# print("This dog has %d legs to run" % self.animal_legs) +# +# # 定义一大堆各种各样的方法 +class Dog(object): + """ + This is a class for Dog + + Dog class is the parents class of all dog, this class contain + general attributes of dog and some common function of dogs, such as + num legs, the voice fucntion, the runing functions. + + Attributes: + name: A string of dog's name + kind: A string of dog's family + age: A integer of dog years + gender: A boolean gender of dog, male=1 of famle=0 + legs A integer if dog's legs + weight: A float of dogs weight + size: A string of dogs, one of big, middle, smal + """ + + def __init__(self, args, gender, size): + """initialize dog class, all attributes pass in with args, which is a dict or indepent params + + Input contain dict and str params, also there is private attribute + + Args: + args.name(str): dog name + args.kind(str): dog family + args.age(int) : dog age + gender(bool) : dog gender, male=1,famale=0 + args.weight(float): dog weight + size(str) : dog size + """ + self.name = args.name + self.kind = args.kind + self.age = args.age + self.weight = args.weight + + # __legs(int) : dog legs,privite attribute, not the inputs params,写在前面用#做注释,不属于输入的参数的初始化 + self.__legs = 4 + """写在后面用三引号__legs(int) : dog legs,privite attribute""" + + self.size = size + self.gender = gender + + def voice(self, size): + """This is dog speak fucntion + + Different dog with different voice + which related to the size,age and kind + + Args: + size(str): dog size + age(int) : dog age + kind(srt): dog kind + + Returns: + None, just print the voice + """ + if size == 'big': + print('Big WangWang') + elif size == 'middle': + print('M wang') + elif size == 'small': + print('Miao') + + # 附注:return 可从任意深度跳出函数,None + + +class Husky(Dog): + """Husky inherent the Dog attris and method""" + + def __init__(self, name, age, color, params): + Dog.__init__(self, name, age) # 利用Dog这个父类的初始化 + self.color = color # 子类中特定属性的初始化 + + def jump(self): + """Husky special jump function""" + print('This dog could jump jump') + + def voice(self): + """重写覆盖父类的函数,实现自己的特殊的方法""" + print('AoAoAoWu~~~~~~') +help(Dog) diff --git a/tasks/task1/submit/test1/note/method.py b/tasks/task1/submit/test1/note/method.py new file mode 100644 index 0000000..cfb6305 --- /dev/null +++ b/tasks/task1/submit/test1/note/method.py @@ -0,0 +1,81 @@ +'''实例方法''' + +class Dog: + def __init__(self, name): + self.name = name + + # 实例方法 + def bark(self): + return "汪汪!我是" + self.name + + # 创建Dog实例 +dog = Dog("小白") + +# 调用实例方法 +print(dog.bark()) # 输出: "汪汪!我是小白" + + +'''类方法是使用@classmethod装饰器定义的方法,在调用时,Python会将类本身传递给第一个参数(通常命名为cls),表示对类进行操作。''' +class MathUtils: + PI = 3.1415926 + + # 类方法 + @classmethod + def circle_area(cls, radius): + return cls.PI * radius * radius + +# 调用类方法 +area = MathUtils.circle_area(5) +print(area) # 输出: 78.539815 +'''在上述代码中,我们使用类方法circle_area计算圆的面积,注意我们在类方法中可以使用类的属性cls.PI''' + +'''静态方法是使用@staticmethod装饰器定义的方法,它不需要特殊的参数(如self或cls)。静态方法与类和实例无关,通常用于执行与类相关的实用函数''' +class StringUtils: + # 静态方法 + @staticmethod + def is_palindrome(s): + return s == s[::-1] + +# 调用静态方法 +result = StringUtils.is_palindrome("level") +print(result) # 输出: True + + + +#特殊方法 +'''特殊方法(魔术方法) +特殊方法,也被称为魔术方法,以双下划线__开头和结尾。它们是Python中用于实现类的特殊行为的方法。''' +#__str__方法 +#__str__方法返回对象的字符串表示,可用于自定义对象在print函数中的输出。 +class Person: + def __init__(self, name, age): + self.name = name + self.age = age + + # 自定义__str__方法 + def __str__(self): + return f"{self.name},{self.age}岁" + + # 创建Person实例 +person = Person("Alice", 30) + +# 调用print函数输出对象 +print(person) # 输出: "Alice,30岁" + + +# __repr__方法返回对象的“官方”字符串表示,可用于在交互式环境中直接输出对象。 +class Point: + def __init__(self, x, y): + self.x = x + self.y = y + + # 自定义__repr__方法 + def __repr__(self): + return f"Point({self.x}, {self.y})" + + # 创建Point实例 +point = Point(1, 2) + +# 在交互式环境中输出对象 +point # 输出: Point(1, 2) + diff --git a/tasks/task1/submit/test1/note/submit.ipynb b/tasks/task1/submit/test1/note/submit.ipynb new file mode 100644 index 0000000..f3ddfee --- /dev/null +++ b/tasks/task1/submit/test1/note/submit.ipynb @@ -0,0 +1,1160 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "e3bd4102-709e-45d9-9f0e-17a934c2cdfd", + "metadata": {}, + "source": [ + "#数据结构List的使用" + ] + }, + { + "cell_type": "raw", + "id": "f852c47d-3132-4d68-a042-8261e2405297", + "metadata": {}, + "source": [ + "1.列表的创建" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "ecf394f1-6853-412f-b940-9f3c490e5b83", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 'dormitory', [{12, 456}, '忙']]" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l1 = [4,2,3]#使用中括号[],每个元素使用逗号间隔,可嵌套创建。\n", + "l2=list(range(7))#使用list()函数\n", + "l3 = list([1,'dormitory',[{12,456},'忙']])#列表为可迭代类型\n", + "l3" + ] + }, + { + "cell_type": "raw", + "id": "fb16b643-a929-4577-8ba3-9a86e6b37fa5", + "metadata": {}, + "source": [ + "列表元素的访问" + ] + }, + { + "cell_type": "raw", + "id": "b366e94e-a6e9-4acb-8965-2ae83e68d63e", + "metadata": {}, + "source": [ + "l3 = [1,'dormitory',[{12,456},'忙']]\n", + "#···········索引···········(正序下标从0开始)\n", + "l3[2]\n", + "l3[-2]\n", + "l3[2][1]\n", + "#··············切片··············\n", + "#可以使用切片操作符 : 来访问列表中的一部分元素。切片操作符 start:stop 会返回从索引 start 到 stop-1 的元素。切片操作符 #start:stop:step 可以指定步长 step\n", + "l4 = ['I','l','o','v','e','p','y','t','h','o','n']\n", + "print(l4[3:])\n", + "print(l4[2:6:2])\n", + "print(l4[::-1])\n", + "print(l4[::])" + ] + }, + { + "cell_type": "raw", + "id": "59bff02d-c62b-4ed4-93ed-fe577e4700b8", + "metadata": {}, + "source": [ + "列表的遍历" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "1539e6fc-c386-43a3-8901-4f4107c7eafd", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 dormitory [{456, 12}, '忙'] 1 dormitory [{456, 12}, '忙'] (0, 1) (1, 'dormitory') (2, [{456, 12}, '忙']) " + ] + } + ], + "source": [ + "#使用in操作符\n", + "for i in l3:\n", + " print(i,end=' ')\n", + "#使用iter()函数\n", + "for i in iter(l3):\n", + " print(i,end=' ')\n", + "#使用enumerate()函数,遍历列表元素及其下标。\n", + "for i in enumerate(l3):\n", + " print(i,end=' ')" + ] + }, + { + "cell_type": "raw", + "id": "9f95af65-fbee-4546-bd83-ac41f8ad1e58", + "metadata": {}, + "source": [ + "列表的排序" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "a4c05653-d092-46d7-a5d7-6a242f00ab93", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['I', 'e', 'h', 'l', 'n', 'o', 'o', 'p', 't', 'v', 'y'] \n", + " [('d', 4), ('g', 3), ('o', 2), ('e', 1)]\n", + "[4, 2, 3] [2, 3, 4]\n" + ] + }, + { + "data": { + "text/plain": [ + "[3, 2, 4]" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#.sort()方法,语法格式:sort(key=none,reverse=False)\n", + "#key表示排列规则。reverse表示排序方式,默认值为False。False表示升序,True表示降序。使用该方法之后,原列表会被排序后的列表覆盖。\n", + "l4.sort()\n", + "l5=[('o',2),('d',4),('e',1),('g',3)]\n", + "l5.sort(key=lambda x:x[1],reverse=True)\n", + "print(l4,'\\n',l5)\n", + "#sorted()方法,将列表元素按要求排列,不覆盖原列表。\n", + "l5=sorted(l1)\n", + "print(l1,l5)\n", + "#reverse()方法,将列表元素降序排列,覆盖原列表\n", + "l1.reverse()\n", + "l1" + ] + }, + { + "cell_type": "markdown", + "id": "3f1eee7a-254e-46b0-abaa-f03797c28985", + "metadata": {}, + "source": [ + "列表的常用方法" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9a1e92d2-900c-4966-a4e2-4df70e6c4cef", + "metadata": {}, + "outputs": [], + "source": [ + "元素的添加" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "d5234230-cf9d-46e6-8407-6b6c9908eb5f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[3, 2, 4, 'function', 'method', 'approach', 'function']\n", + "[3, 2, 4, 'function', 'method', 'approach', 'function', 'method', 'approach']\n", + "[0, 1, 2, 3, 'jk', 4, 5, 6]\n", + "[0, 1, 2, 3, 'jk', 4, 5, 6, 'hfhf']\n" + ] + } + ], + "source": [ + "#list.append(obj),用于在列表末尾添加新的元素。\n", + "l1.append('function')\n", + "print(l1)\n", + "#list.exend(seq),用于在列表末尾一次性添加另一个列表中的所有元素。seq表示列表,可以是字典、元组、集合、字典,若为字典,则仅会将键作为元素依次添加到原列表的末尾\n", + "l1.extend(['method','approach'])\n", + "print(l1)\n", + "#insert()方法,用于将元素插入列表的指定位置。list.insert(index,obj),若指定的位置不存在,则插入到列表末尾。\n", + "l2.insert(4,'jk')#在索引为1的位置插入\n", + "print(l2)\n", + "l2.insert(9,'hfhf')#该索引不存在,即越界,在末尾插入\n", + "print(l2)" + ] + }, + { + "cell_type": "raw", + "id": "03943cd7-6631-438c-b62c-1a0df5deaaba", + "metadata": {}, + "source": [ + "元素的删除" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "034144d6-9717-4f78-ba32-e00e1415f9fd", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[3, 'math', 'function']\n", + "[3, 'math']\n" + ] + } + ], + "source": [ + "#del语句,删除列表中指定位置的元素。只会移除匹配到的第一个元素\n", + "l1.remove('approach')#移除首个匹配的元素\n", + "print(l1)\n", + "#pop()方法 list.pop([index=-1])\n", + "l1.pop(2)\n", + "print(l1)\n", + "#clear(),clear() 方法用于移除列表中的所有元素。\n", + "l6 = ['chinese','english','physics','english']\n", + "l6.clear()" + ] + }, + { + "cell_type": "raw", + "id": "d6d779b7-a494-4bca-aa65-4dac105543ad", + "metadata": {}, + "source": [ + "元素的修改" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "2ed46d71-0f21-435b-8f3f-c6ef9ecf19fe", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[3, 'math', 'function', 'approach']\n" + ] + } + ], + "source": [ + "#通过索引获取元素并对其重新赋值。\n", + "l1[1]='math'\n", + "print(l1)" + ] + }, + { + "cell_type": "raw", + "id": "6b2e17e9-66fd-4ba3-a0d9-88bf76898d39", + "metadata": {}, + "source": [ + "列表复制" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "a44457fb-fe6b-421f-95b7-2a44031699b8", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['关羽', '张飞', '赵云', '马超']\n", + "['关羽', '张飞', '赵云', '马超']\n", + "2357558114176\n", + "2357558114176\n", + "['法正', '马良', ['郭嘉', '庞统']]\n", + "['法正', '马良', ['诸葛亮', '庞统']]\n", + "2357558137792\n", + "2357557566144\n" + ] + } + ], + "source": [ + "#直接复制\n", + "willList = [\"关羽\",\"张飞\",\"赵云\",\"马超\",\"黄忠\"]\n", + "willList_copy1 = willList #直接复制\n", + "willList.pop();\n", + "print(willList)\n", + "print(willList_copy1)\n", + "print(id(willList))\n", + "print(id(willList_copy1))\n", + "#浅复制。复制方法的复制过程是将原列表复制一份,赋值给新的列表\n", + "import copy\n", + "willlist = [\"法正\",\"马良\",[\"诸葛亮\",\"庞统\"]]\n", + "willlist1 = copy.copy(willlist)\n", + "willlist2 = willlist[:]\n", + "willlist3 = list(willlist)\n", + "#深复制。深复制,除了顶层复制,还对子元素也进行了复制。经过深复制后,原始对象和复制对象所有的可变元素地址都没有相同的\n", + "willlist = [\"法正\",\"马良\",[\"诸葛亮\",\"庞统\"]]\n", + "willlist1 = copy.deepcopy(willlist)\n", + "willlist[2][0] = \"郭嘉\"\n", + "print(willlist)\n", + "print(willlist1)\n", + "print(id(willlist))\n", + "print(id(willlist1))" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "f3615a84-63c8-477d-ba03-087d400918fb", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "english的索引为: 1\n" + ] + } + ], + "source": [ + "#元素索引的查找,查找元素出现的第一个索引。\n", + "l1 = ['chinese','english','physics','english']\n", + "print(\"english的索引为:\",l1.index('english'))\n", + "#计元素数\n", + "l1 = ['chinese','english','physics','english']\n", + "print(\"english的个数为:\",l1.count('english'))\n", + "# count(),count() 方法用于返回列表中某个元素的出现次数。\n", + "numbers = [1, 2, 3, 2, 2]\n", + "count_of_two = numbers.count(2)\n", + "print(count_of_two) # 输出 3" + ] + }, + { + "cell_type": "markdown", + "id": "df29fde6-33fa-42b4-a6ce-cbad9146193a", + "metadata": {}, + "source": [ + "#数据结构dict的使用" + ] + }, + { + "cell_type": "raw", + "id": "7dda38bb-0fae-4a11-947b-28e05bb4f158", + "metadata": {}, + "source": [ + "字典的创建:dict(),{}" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "id": "ca747967-0723-4daf-aa05-4b4cdf204982", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'apple': 3, 'orange': 5, 'grape': 10}\n", + "{'tomato': None, 'potato': None}\n", + "{'tomato': 10, 'potato': 10}\n" + ] + } + ], + "source": [ + "#dict(),创建重复键的字典,报错,d2 = dict(apple=3,orange=5,grape=10,grape=50)\n", + "d1 = dict(apple=3,orange=5,grape=10)\n", + "print(d1)\n", + "#fromkeys()方法,用于统一将传入字典的键对应的值设置为预置值或者None。d1 = dict.fromkeys(iterable,value),可迭代类型,预置值(默认为None)\n", + "d1 = dict.fromkeys(('tomato','potato'))#未设置value\n", + "print(d1)\n", + "d2 = dict.fromkeys(('tomato','potato'),10)#设置value\n", + "print(d2)" + ] + }, + { + "cell_type": "raw", + "id": "6861c290-83a5-49e9-802e-231813a01637", + "metadata": {}, + "source": [ + "字典元素的访问,查询" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "887e4bb1-39e5-4732-9016-04cf78144843", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3\n", + "dict_items([('apple', 3), ('orange', 5), ('grape', 10)])\n", + "dict_keys(['apple', 'orange', 'grape'])\n", + "dict_values([3, 5, 10])\n", + "10\n", + "None\n", + "60\n", + "1\n", + "None\n", + "{'apple': 1, 'orange': 5, 'grape': 10, 'strawberry': 20, 'banana': None}\n", + "90\n", + "{'apple': 1, 'orange': 5, 'grape': 10, 'strawberry': 20, 'banana': None, 'app': 90}\n" + ] + } + ], + "source": [ + "d1 = dict(apple=3,orange=5,grape=10)\n", + "print(d1['apple'])#访问字典中存在的键的值\n", + "print(d1.items())#查询所有元素items()方法,该对象支持迭代操作,可以遍历\n", + "print(d1.keys())#查询所有键keys()方法,该对象支持迭代操作,可以遍历\n", + "print(d1.values())#查询所有值values()方法,该对象支持迭代操作,可以遍历)\n", + "#查询键对应的值get()方法\n", + "d1 = {'apple':1,'orange':5,'grape':10,'strawberry':20}\n", + "print(d1.get('grape'))#字典中该键存在,返回对应的值\n", + "print(d1.get('banana'))#字典中该键不存在,返回空值\n", + "print(d1.get('banana',60))#字典中该键不存在,返回预置\n", + "#查询键对应的值并适时添加键值对setdefault()方法\n", + "print(d1.setdefault('apple'))#该键存在,返回对应值\n", + "print(d1.setdefault('banana'))#该键不存在,存入新键值对,预置值缺省,返回None\n", + "print(d1)\n", + "print(d1.setdefault('app',90))#该键不存在,存入新键值对,预置值已设置,返回预置值\n", + "print(d1)" + ] + }, + { + "cell_type": "raw", + "id": "1a93b8e3-3855-4d49-99a8-5e029767045a", + "metadata": {}, + "source": [ + "字典的其他操作" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "id": "a042abc7-f13f-491d-8977-5e97db66374a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'apple': 1, 'orange': 5, 'grape': 10, 'strawberry': 20, 'banana': None, 'app': 90}\n", + "{'apple': 1, 'orange': 5, 'grape': 10, 'strawberry': 20, 'banana': None, 'app': 90}\n", + "10 {'apple': 1, 'orange': 5, 'strawberry': 20, 'banana': None, 'app': 90}\n" + ] + } + ], + "source": [ + "#字典元素的添加\n", + "d1.update(grape = 10)\n", + "print(d1)\n", + "d1['strawberry'] = 20\n", + "print(d1)\n", + "#删除\n", + "#pop()方法,dict.pop(key[,default])\n", + "#第一个参数是字典中要删除的键,第二个参数是预置值。当字典中存在该键,则返回其对应的值;\n", + "#当字典中不存在该键,则返回预先设置好的预置值;当预置值缺省且该键不存在,报KeyError的异常。\n", + "a = d1.pop('grape')#删除存在的键,返回该键对应的值\n", + "print(a,d1)\n", + "#popitem()方法,用于随机删除字典中的元素。\n", + "#clear()方法,用于清空字典中的元素\n", + "#del语句,通过指定键来删除该键值对。del语句也可以删除整个字典对象。\n", + "d1 = {'apple':1,'orange':5,'grape':10,'strawberry':20}\n", + "del d1['apple']#指定键来删除该键值对" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "id": "9a86ac11-384c-4af6-98e6-8d850cfcb896", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "apple 1\n", + "orange 5\n", + "grape 10\n", + "strawberry 20\n", + "('apple', 1)\n", + "('orange', 5)\n", + "('grape', 10)\n", + "('strawberry', 20)\n", + "apple\n", + "orange\n", + "grape\n", + "strawberry\n", + "1\n", + "5\n", + "10\n", + "20\n" + ] + } + ], + "source": [ + "#字典的迭代\n", + "d1 = {'apple':1,'orange':5,'grape':10,'strawberry':20}\n", + "for k,v in d1.items():#键和值分别输出\n", + " print(k,v)\n", + "for i in d1.items():#以键值对的形式输出\n", + " print(i)\n", + "for k in d1.keys():\n", + " print(k)\n", + "for v in d1.values():\n", + " print(v)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "id": "2265451b-595f-404d-a637-288676892654", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n", + "False\n", + "True\n", + "False\n", + "键值对个数为 4\n" + ] + } + ], + "source": [ + "#判断键是否存在于字典\n", + "#判断值时,可以直接使用字典名\n", + "print('orange' in d1.keys())#判断该键是否在字典中\n", + "print('orange' not in d1.keys())#判断该键是否不在字典中\n", + "print('orange' not in d1)#判断该键是否不在字典中\n", + "print(10 in d1.values())#判断该值是否在字典中\n", + "print(10 not in d1.values())#判断该值是否不在字典中\n", + "#计算字典中键值对的个数\n", + "d1 = {'apple':1,'orange':5,'grape':10,'strawberry':20}\n", + "print('键值对个数为',len(d1))#计算键值对的个数" + ] + }, + { + "cell_type": "markdown", + "id": "5a362cb5-17ab-4bd8-861d-f196c568bb89", + "metadata": {}, + "source": [ + "lambda 语法格式:\r\n", + "lambda arguments: expressi\n", + "lambda是 Python 的关键字,用于定义 lambda 函数。\r\n", + "arguments 是参数列表,可以包含零个或多个参数,但必须在冒号(:)前指定。\r\n", + "expression 是一个表达式,用于计算并返回函数的结果。on" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "id": "05c826c7-5e09-47dc-887c-1dd7c06ce87e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, world!\n", + "15\n", + "30\n" + ] + } + ], + "source": [ + "f = lambda: \"Hello, world!\"\n", + "print(f()) \n", + "x = lambda a : a + 10\n", + "print(x(5))\n", + "x = lambda a, b : a * b\n", + "print(x(5, 6))" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "id": "0979fc68-53d7-4a04-ad0b-0071fee4702b", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 4, 9, 16, 25]\n", + "[2, 4, 6, 8]\n" + ] + } + ], + "source": [ + "numbers = [1, 2, 3, 4, 5]\n", + "squared = list(map(lambda x: x**2, numbers))\n", + "print(squared) # 输出: [1, 4, 9, 16, 25]\n", + "numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n", + "even_numbers = list(filter(lambda x: x % 2 == 0, numbers))\n", + "print(even_numbers) # 输出:[2, 4, 6, 8]" + ] + }, + { + "cell_type": "markdown", + "id": "818063f2-a9e3-4512-91cf-7396c673fc29", + "metadata": {}, + "source": [ + "Decorator装饰器\n", + "装饰器是 Python 中的一种高级功能,允许动态地修改函数或类的行为。\r\n", + "装饰器是一种函数,它接受一个函数作为参数,并返回一个新的函数或修改原来的函数\r\n", + "\r\n", + "装饰器的语法使用 @decorator_name 来应用在函数或方上。\r\n", + "\r\n", + "Python 还提供了一些内置的装饰器,比如 @staticmethod 和 @classmethod,用于定义静态(整理在其他地方)方法和类方法" + ] + }, + { + "cell_type": "raw", + "id": "45bd22fc-5121-420b-80d3-89c7af7147e4", + "metadata": {}, + "source": [ + "#基本语法(不带参数)\n", + "def decorator_function(original_function):\n", + " def wrapper(*args, **kwargs):\n", + " # 这里是在调用原始函数前添加的新功能\n", + " before_call_code()\n", + " \n", + " result = original_function(*args, **kwargs)\n", + " \n", + " # 这里是在调用原始函数后添加的新功能\n", + " after_call_code()\n", + " \n", + " return result\n", + " return wrapper\n", + "\n", + "# 使用装饰器\n", + "@decorator_function\n", + "def target_function(arg1, arg2):\n", + " pass # 原始函数的实现\n", + "\n", + "#(带参数)\n", + "def repeat(n):\n", + " def decorator(func):\n", + " def wrapper(*args, **kwargs):\n", + " for _ in range(n):\n", + " result = func(*args, **kwargs)\n", + " return result\n", + " return wrapper\n", + " return decorator\n", + "\n", + "@repeat(3)\n", + "def greet(name):\n", + " print(f\"Hello, {name}!\")\n", + "\n", + "greet(\"Alice\")" + ] + }, + { + "cell_type": "markdown", + "id": "3bc4ab2c-048f-4f22-97c1-2cf2d7de361c", + "metadata": {}, + "source": [ + "re正则表达式的使用。\n", + " 一种文本模式,通过特殊的语法规则来定义字符串的匹配模式。通过正则表达式,可以描述字符串的模式,并能够对文本进行匹配、查找、替换等操作。\n", + "正则表达式的大致匹配过程是:\r\n", + "1.依次拿出表达式和文本中的字符比较,\r\n", + "2.如果每一个字符都能匹配,则匹配成功;一旦有匹配不成功的字符则匹配失败。\r\n", + "3.如果表达式中有量词或边界,这个过程会稍微有一些不同。" + ] + }, + { + "cell_type": "raw", + "id": "dbfab4de-9a09-4e50-9787-232c6af13bc8", + "metadata": {}, + "source": [ + "正则表达式的核心语法" + ] + }, + { + "cell_type": "raw", + "id": "bce166db-cfec-44f8-9ddf-21f5e2e1247a", + "metadata": {}, + "source": [ + "字符类:\n", + "\\d:匹配任何数字,等同于[0-9]。\n", + "\\w:匹配字母、数字或下划线,等同于[a-zA-Z0-9_]。\n", + "\\s:匹配任何空白字符(空格、制表符、换行符等)。\n", + "\\D:匹配任何非数字字符。\n", + "\\W:匹配任何非字母数字字符。\n", + "\\S:匹配任何非空白字符。\n", + "\n", + "量词:\n", + "*:匹配前面的子表达式零次或多次。\n", + "+:匹配前面的子表达式一次或多次。\n", + "?:匹配前面的子表达式零次或一次。\n", + "{n}:匹配前面的子表达式恰好n次。\n", + "{n,}:匹配前面的子表达式至少n次。\n", + "{n,m}:匹配前面的子表达式n到m次。\n", + "\n", + "边界匹配:\n", + "^:匹配字符串的开始。\n", + "$:匹配字符串的结束。\n", + "分组与捕获:\n", + "():用于分组,可以提取匹配的部分。\n", + "|:表示“或”操作,匹配左边或右边的子表达式。\n", + "\n", + "转义字符:\n", + "\\:用于转义特殊字符。例如,\\.表示匹配字面意义上的点号。\n" + ] + }, + { + "cell_type": "raw", + "id": "283824cf-63f2-4136-8974-10c4af4c6086", + "metadata": {}, + "source": [ + "re模块常用方法" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "id": "9293e6ae-13bf-4fc5-9a23-6fc40c138701", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "123\n", + "123\n", + "['123', '456']\n", + "123\n", + "456\n", + "abcXxyzX\n", + "['abc', 'xyz', '']\n" + ] + } + ], + "source": [ + "import re\n", + "#re.match()。从字符串的起始位置匹配一个正则表达式。如果匹配成功,返回一个匹配对象;如果不匹配,则返回None。\n", + "result = re.match(r'\\d+', '123abc')\n", + "print(result.group()) \n", + "\n", + "#re.search():扫描整个字符串,找到第一个匹配的子串。如果找到匹配,返回匹配对象,否则返回None。\n", + "result = re.search(r'\\d+', 'abc123xyz')\n", + "print(result.group()) #\n", + "\n", + "#re.findall():返回字符串中所有匹配正则表达式的子串,返回一个列表。如果没有匹配,返回空列表。\n", + "result = re.findall(r'\\d+', 'abc123xyz456')\n", + "print(result) \n", + "\n", + "#re.finditer():re.findall()类似,但它返回的是一个迭代器,每个元素是一个匹配对象。它允许我们获取更详细的匹配信息,如匹配的开始和结束位置。\n", + "result = re.finditer(r'\\d+', 'abc123xyz456')\n", + "for match in result:\n", + " print(match.group()) \n", + " \n", + "#re.sub():替换字符串中匹配正则表达式的部分。它的第一个参数是正则表达式,第二个参数是替换的字符串,第三个参数是目标字符串。\n", + "result = re.sub(r'\\d+', 'X', 'abc123xyz456')\n", + "print(result) \n", + "\n", + "#re.split():re.split()根据匹配的正则表达式来分割字符串。返回值是一个列表。\n", + "result = re.split(r'\\d+', 'abc123xyz456')\n", + "print(result) " + ] + }, + { + "cell_type": "markdown", + "id": "8f5d50a3-6da7-444c-b6f5-03f0bedfef0b", + "metadata": {}, + "source": [ + "列表推导式(生成式)——List Comprehensions,Python内置的非常简单却强大的可以用来创建list的生成式。列表推导式可以利用 range 区间、元组、列表、字典和集合等数据类型,快速生成一个满足指定需求的列表。" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "id": "24c59d1d-8cbd-436b-b6bd-eb2b556a399d", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[4, 16, 36, 64, 100]\n", + "[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3), (4, 0), (4, 1), (4, 2), (4, 3)]\n" + ] + } + ], + "source": [ + "#[表达式 for 迭代变量 in 可迭代对象 [if 条件表达式] ]\n", + "print([x * x for x in range(1, 11) if x % 2 == 0])\n", + "[m + n for m in 'ABC' for n in 'XYZ']\n", + "d_list = [(x, y) for x in range(5) for y in range(4)]\n", + "print(d_list)" + ] + }, + { + "cell_type": "markdown", + "id": "2bd02bac-4805-48bd-a2fc-c61d7a8fd1a1", + "metadata": {}, + "source": [ + "generator生成器(yield关键字)" + ] + }, + { + "cell_type": "raw", + "id": "1137988f-2b76-49ac-abb7-ce63c017aa64", + "metadata": {}, + "source": [ + "生成器有两种表示:生成器表达式,生成器函数" + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "id": "5f9adab4-7586-4a00-ae96-cec4cce25075", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n" + ] + } + ], + "source": [ + "#生成器表达式:圆括号来创建生成器,其语法与推导式相同,只是将 [] 换成了 () 。 生成器表达式会产生一个新的生成器对象。\n", + "#这种生成器表达式被成为隐式生成器,他是禁止使用 yield 和 yield from 表达式\n", + "print(type([i for i in range(5)]))\n", + "type((i for i in range(5)))\n", + "a = (i for i in range(5))\n", + "for i in a:\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 72, + "id": "6209f15d-0b09-4135-b9e2-3341b37ea8fa", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1]\n", + "[1, 1]\n", + "[1, 2, 1]\n", + "[1, 3, 3, 1]\n", + "[1, 4, 6, 4, 1]\n", + "[1, 5, 10, 10, 5, 1]\n", + "[1, 6, 15, 20, 15, 6, 1]\n", + "[1, 7, 21, 35, 35, 21, 7, 1]\n", + "[1, 8, 28, 56, 70, 56, 28, 8, 1]\n", + "[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]\n" + ] + } + ], + "source": [ + "#生成器函数。函数如果包含 yield 指令,该函数调用的返回值是一个生成器对象,\n", + "#此时函数体中的代码并不会执行,只有显示或隐示地调用 next 的时候才会真正执行里面的代码。\n", + "#yield可以暂停一个函数并返回此时的中间结果。该函数将保存执行环境并在下一次恢复。\n", + "#调用generator函数会创建一个generator对象,多次调用generator函数会创建多个相互独立的generator。\n", + "def triangles():\n", + " row = [1]\n", + " while True:\n", + " yield row\n", + " row = [1] + [row[i] + row[i + 1] for i in range(len(row) - 1)] + [1]\n", + "n = 0\n", + "results = []\n", + "for t in triangles():\n", + " results.append(t)\n", + " n = n + 1\n", + " if n == 10:\n", + " break\n", + "\n", + "for t in results:\n", + " print(t)" + ] + }, + { + "cell_type": "raw", + "id": "31f29207-fdda-4938-829f-240c684fe78d", + "metadata": {}, + "source": [ + " 可以通过 close() 手动关闭生成器函数,后面再调用生成器会直接返回 StopIteration异常\n", + " 如果一个函数包含 yield 关键字,那么这个函数的返回值是一个生成器,但是这个函数仅是一个函数而已。使用这个函数返回一个生成器对象并使用它才是真正的目的。此时,在生成器函数使用 return 对其并没有任何影响,这个函数返回的仍然是生成器对象。但是,如果没有 return 语句,则执行到函数完毕时将返回 StopIteration 异常。 如果在执行过程中遇到 return 语句,则直接抛出 StopIteration 异常,终止迭代。如果在 return 后返回一个值,那么这个值作为 StopIteration 异常的说明,不是函数的返回值\n" + ] + }, + { + "cell_type": "code", + "execution_count": 81, + "id": "257841c4-56d1-46b7-ab33-1a690aad457a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "Start...\n", + "0\n", + "Start...\n", + "1\n", + "Start...\n", + "2\n", + "Start...\n", + "3\n", + "Start...\n", + "4\n" + ] + }, + { + "ename": "StopIteration", + "evalue": "3", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mStopIteration\u001b[0m Traceback (most recent call last)", + "Cell \u001b[1;32mIn[81], line 10\u001b[0m\n\u001b[0;32m 8\u001b[0m f\u001b[38;5;241m=\u001b[39mfun()\n\u001b[0;32m 9\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;241m6\u001b[39m):\n\u001b[1;32m---> 10\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;28mnext\u001b[39m(f),end\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 11\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mhello\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n", + "\u001b[1;31mStopIteration\u001b[0m: 3" + ] + } + ], + "source": [ + "def fun():\n", + " for i in range(5):\n", + " print(\"Start...\")\n", + " yield i\n", + " return 3\n", + "print(fun)\n", + "print(fun())\n", + "f=fun()\n", + "for i in range(6):\n", + " print(next(f),end=\"\\n\")\n", + "print(\"hello\")" + ] + }, + { + "cell_type": "markdown", + "id": "11ff5ca9-f3c5-4c9a-ae15-7f30ba5f275b", + "metadata": {}, + "source": [ + "类型提示(typing hint)" + ] + }, + { + "cell_type": "code", + "execution_count": 84, + "id": "1b86e22b-8b21-46bc-b4b6-904415e125f0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hi,Tom\n", + "Hi,123\n" + ] + } + ], + "source": [ + "#给函数参数、返回值添加类型注解的语法为:\n", + "#(parameter: type) # 函数参数类型注解 -> type # 返回值类型注解\n", + "def say_hi(name: str) -> str:#name参数的类型为:str.并且 -> str 表示函数的返回值也是str\n", + " return f'Hi,{name}'\n", + "greeting = say_hi(\"Tom\")\n", + "print(greeting)\n", + "#Python 解释器完全忽略了类型提示。如果将数字传递给函数,程序将运行,而不会出现任何警告或错误\n", + "greeting = say_hi(123)\n", + "print(greeting)" + ] + }, + { + "cell_type": "raw", + "id": "b1faaadb-1836-4c38-b01f-e1e8b1a95a93", + "metadata": {}, + "source": [ + "典例\n", + "def process_numbers(numbers: List[int]) -> List[str]:\n", + " return [str(num) for num in numbers]\n", + "\n", + "def calculate_total(data: Dict[str, int]) -> int:\n", + " return sum(data.values())\n", + "\n", + "def format_date(date: datetime) -> str:\n", + " return date.strftime(\"%Y-%m-%d\")\n", + "​\n", + "def process_data(data: Union[List[int], List[str]]) -> List[str]:\n", + " if isinstance(data, list):\n", + " return [str(item) for item in data]\n", + " else:\n", + " return []\n", + "​\n", + "def generate_numbers() -> Generator[int, None, None]:\n", + " for i in range(10):\n", + " yield i\n", + "​\n", + "class MyClass:\n", + " def __init__(self, value: int):\n", + " self.value = value\n", + " \n", + " def double_value(self) -> \"MyClass\":\n", + " return MyClass(self.value * 2)" + ] + }, + { + "cell_type": "raw", + "id": "c918de81-9328-4956-b607-5144f3bbb73b", + "metadata": {}, + "source": [ + "Python类型提示检查器工具:mypy" + ] + }, + { + "cell_type": "raw", + "id": "d1e818ff-2dce-45dd-b95c-ef6a95f6a793", + "metadata": {}, + "source": [ + "通过类型提示使变量类型保持一致,定义变量时,可以添加类型提示" + ] + }, + { + "cell_type": "code", + "execution_count": 93, + "id": "e53c1fdf-b153-4072-b641-cf3cab9d6e96", + "metadata": {}, + "outputs": [], + "source": [ + "import mypy\n", + "name: str = 'John'#变量的类型是str。如果将非字符串的值分配给变量,静态类型检查器将发出错误。\n", + "name: str = 'Hello'" + ] + }, + { + "cell_type": "raw", + "id": "7504928d-5a94-4bd2-91c1-f6022afb5767", + "metadata": {}, + "source": [ + "联合类型提示,允许1个变量接受2种类型以上的输入值\n", + "从 Python 3.10 开始,您可以使用 X | Y 用于创建联合类型" + ] + }, + { + "cell_type": "code", + "execution_count": 94, + "id": "1d1770e5-c006-4ad8-91d5-13c98b92b406", + "metadata": {}, + "outputs": [], + "source": [ + "from typing import Union\n", + "def add(x: Union[int, float], y: Union[int, float]) -> Union[int, float]:\n", + " return x + y" + ] + }, + { + "cell_type": "code", + "execution_count": 95, + "id": "1db59959-6a20-4192-88c6-fd9b68f50bc6", + "metadata": {}, + "outputs": [], + "source": [ + "#类型别名,Python 允许您为类型分配别名,并将别名用于类型提示。例如:\n", + "from typing import Union\n", + "number = Union[int, float]\n", + "def add(x: number, y: number) -> number:\n", + " return x + y" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e48df4ef-06e1-46f5-a741-8f7f14e70611", + "metadata": {}, + "outputs": [], + "source": [ + "简单容器类型的类型提示(Typing 模块的 LIst, Tuple, Set,Dict, Sequence等封装类)\n", + "Typing 类型名\t Python内置类型\n", + "List\t list\n", + "Tuple\t tuple\n", + "Dict\t dict\n", + "Set\t set\n", + "Sequence\t 用于表示 list, tuple 类型\n", + "Mapping\t 用于表示字典,set 类型\n", + "ByteString\t bytes, bytearray, 以及 memoryview 等二进制类型." + ] + }, + { + "cell_type": "code", + "execution_count": 107, + "id": "48f2bff9-69f5-43c3-9fd0-18de6f589d68", + "metadata": {}, + "outputs": [], + "source": [ + " \n", + "from typing import List,Sequence,Tuple,Mapping\n", + "\n", + "ratings: List[int] = [1, 2, 3]\n", + "data: Sequence = [1,2,3]\n", + "x: Tuple[int] = (5,)\n", + "y: Tuple[int, str] = (5, \"foo\")\n", + "x: Mapping[str, str | int] = {} \n", + "x['name']=3.113 # 会提示错误\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "94f42523-6bda-45de-8ca2-f90965acd9eb", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.7" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/tasks/task1/submit/test1/pokemon_game/effects.py b/tasks/task1/submit/test1/pokemon_game/effects.py new file mode 100644 index 0000000..6ae0a31 --- /dev/null +++ b/tasks/task1/submit/test1/pokemon_game/effects.py @@ -0,0 +1,56 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from pokemon import Pokemon + + +class Effect: + name: str + + def __init__(self, duration: int) -> None: + # 初始化效果持续时间 + self.duration = duration + + def apply(self, pokemon: "Pokemon") -> None: + # 应用效果的抽象方法,子类需要实现 + raise NotImplementedError + + def decrease_duration(self) -> None: + # 减少效果持续时间 + self.duration -= 1 + print(f"{self.name} effect duration decreased. Remaining: {self.duration}") + + +class PoisonEffect(Effect): + name = "Poison" + + def __init__(self, damage: int = 10, duration: int = 3) -> None: + super().__init__(duration) + self.damage = damage + + def apply(self, pokemon: "Pokemon") -> None: + pokemon.receive_damage(self.damage) + print(f"{pokemon.name} takes {self.damage} poison damage!") + + +class HealEffect(Effect): + name = "Heal" + + def __init__(self, amount: int, duration: int = 3) -> None: + super().__init__(duration) + self.amount = amount + + def apply(self, pokemon: "Pokemon") -> None: + pokemon.heal_self(self.amount) + print(f"{pokemon.name} heals {self.amount} HP!") + +class BurnEffect(Effect): + name="Burn" + #“烧伤”状态(每回合受到10额外伤害, 持续2回合) + def __init__(self, damage: int=10, duration: int = 2) -> None: + super().__init__(duration) + self.damage = damage + + def apply(self, pokemon: "Pokemon") -> None: + pokemon.receive_damage(self.damage) + print(f"{pokemon.name} takes {self.damage} burn damage!") diff --git a/tasks/task1/submit/test1/pokemon_game/main.py b/tasks/task1/submit/test1/pokemon_game/main.py new file mode 100644 index 0000000..49adb10 --- /dev/null +++ b/tasks/task1/submit/test1/pokemon_game/main.py @@ -0,0 +1,7 @@ + +import play + + + +if __name__ == "__main__": + play.play1.run() diff --git a/tasks/task1/submit/test1/pokemon_game/play.py b/tasks/task1/submit/test1/pokemon_game/play.py new file mode 100644 index 0000000..84df496 --- /dev/null +++ b/tasks/task1/submit/test1/pokemon_game/play.py @@ -0,0 +1,160 @@ +from __future__ import annotations +import pokemon +import copy +import random +import sys + + + + +def valid_choice(choice, range): + # 判断输入的选择是否合法 + return choice.isdigit() and 1 <= int(choice) <= range + + +class Play: + def __init__(self, all_pokemon) -> None: + self.all_pokemon = all_pokemon + self.player_team = [] + self.computer_team = [] + self.current_player_pokemon = None + self.current_computer_pokemon = None + self.turn = 0 + + + + def player_choose_pokemon_team(self, pokemon_to_choose: list, num=2): + # 玩家选择队伍中的Pokemon + print(f"Choose {num} pokemon for your team:") + pokemon_to_choose = copy.copy(pokemon_to_choose) + index = 0 + while len(self.player_team) < num: + self.print_pokemon_list(pokemon_to_choose) + choice = input(f"Select your pokemon {index} by number: ") + if valid_choice(choice, len(pokemon_to_choose)): + self.player_team.append(pokemon_to_choose.pop(int(choice) - 1)) + index += 1 + else: + print("Invalid choice, please select a valid Pokemon") + print("Here is your pokemon team:") + self.print_pokemon_list(self.player_team) + + def computer_choose_pokemon_team(self, pokemon_to_choose: list, num=2): + # 电脑选择对战的队伍 + print(f"Your opponent is choosing {num} pokemon") + self.computer_team.extend(random.sample(pokemon_to_choose, num)) + print("Here is your opponent's team:") + self.print_pokemon_list(self.computer_team) + + def print_pokemon_list(self, pokemon_list): + # 打印Pokemon列表 + for i, p in enumerate(pokemon_list, 1): + print(f"{i}: {p}") + + def player_choose_pokemon(self): + # 玩家选择当前战斗的Pokemon + print("Your Team:") + self.print_pokemon_list(self.player_team) + while True: + choice = input("Select your pokemon to battle by number:") + if valid_choice(choice, len(self.player_team)): + chosen_pokemon = self.player_team[int(choice) - 1] + if chosen_pokemon.alive is True: + print(f"You choosed {chosen_pokemon.name}") + self.current_player_pokemon = chosen_pokemon + return chosen_pokemon # 返回选择的Pokemon + else: + print(f"{chosen_pokemon.name} has fainted! Choose another Pokemon!") + else: + print("Invalid choice, please select a valid Pokemon") + + def computer_choose_pokemon(self): + # 电脑随机选择一个存活的Pokemon + available_pokemon = [p for p in self.computer_team if p.alive is True] + chosen_pokemon = random.choice(available_pokemon) + print(f"Your opponent choosed {chosen_pokemon}") + self.current_computer_pokemon = chosen_pokemon + return chosen_pokemon # 返回选择的Pokemon + + def game_finished(self): + # 游戏结束 + sys.exit() + + def check_game_status(self): + # 检查游戏状态,判断玩家或电脑是否失败 + is_player_fail = all(pokemon.alive is False for pokemon in self.player_team) + is_computer_fail = all(pokemon.alive is False for pokemon in self.computer_team) + if is_player_fail and is_computer_fail: + print("All your and opponent's Pokemon have fainted. The game is tied.") + self.game_finished() + elif not is_player_fail and is_computer_fail: + print("All computer's Pokemon have fainted. You win!") + self.game_finished() + elif is_player_fail and not is_computer_fail: + print("All your Pokemon have fainted. You lose!") + self.game_finished() + + if not self.current_player_pokemon.alive: + self.player_choose_pokemon() + if not self.current_computer_pokemon.alive: + self.computer_choose_pokemon() + + def player_use_skills(self): + # 玩家选择技能 + print("Choose the skill your pokemon to use") + skills = self.current_player_pokemon.skills + for i, skill in enumerate(skills, 1): + print(f"{i}: {skill}") + choice = input("Select the skill you want to use by number:") + if valid_choice(choice, len(skills)): + player_skill = self.current_player_pokemon.skills[int(choice) - 1] + self.current_player_pokemon.use_skill( + player_skill, self.current_computer_pokemon + ) + else: + print("Invalid choice, please select a valid Skill") + + def computer_use_skills(self): + # 电脑随机选择技能 + computer_skill = random.choice(self.current_computer_pokemon.skills) + self.current_computer_pokemon.use_skill( + computer_skill, self.current_player_pokemon + ) + + def battle_round_begin(self): + # 回合开始 + self.turn +=1 + self.current_player_pokemon.begin() + self.current_computer_pokemon.begin() + self.check_game_status() + + def battle_round(self): + # 回合进行 + print( + f"\n{self.current_player_pokemon.name} vs {self.current_computer_pokemon.name}" + ) + self.player_use_skills() + self.computer_use_skills() + self.check_game_status() + + def run(self): + # 游戏主循环 + self.player_choose_pokemon_team(self.all_pokemon) + self.computer_choose_pokemon_team(self.all_pokemon) + + print("Choose Your First Pokemon to battle") + self.current_player_pokemon = self.player_choose_pokemon() + self.current_computer_pokemon = self.computer_choose_pokemon() + + while True: + self.battle_round_begin() + self.battle_round() + + +def all_pokemon(): + pokemon1 = pokemon.Bulbasaur() + pokemon2 = pokemon.Charmander() + return [pokemon1, pokemon2] + +all_pokemon=all_pokemon() +play1= Play(all_pokemon) \ No newline at end of file diff --git a/tasks/task1/submit/test1/pokemon_game/pokemon.py b/tasks/task1/submit/test1/pokemon_game/pokemon.py new file mode 100644 index 0000000..8991a43 --- /dev/null +++ b/tasks/task1/submit/test1/pokemon_game/pokemon.py @@ -0,0 +1,176 @@ +from __future__ import annotations +import skills +from skills import Skill +from effects import Effect +from random import randint +import play + +class Pokemon: + name: str + type: str + + def __init__(self, hp: int, attack: int, defense: int,evade:int) -> None: + # 初始化 Pokemon 的属性 + self.hp = hp + self.max_hp = hp + self.attack = attack + self.defense = defense + self.skills = self.initialize_skills() + self.evade=evade #初始化闪避率 + self.alive = True + self.statuses = [] + + def initialize_skills(self): + # 抽象方法,子类应实现具体技能初始化 + raise NotImplementedError + + def use_skill(self, skill: Skill, opponent: Pokemon): + # 使用技能 + print(f"{self.name} uses {skill.name}") + skill.execute(self, opponent) + + def heal_self(self, amount): + # 为自身恢复生命值 + if not isinstance(amount, int): + amount = int(amount) + + self.hp += amount + if self.hp > self.max_hp: + self.hp = self.max_hp + print(f"{self.name} heals {amount} HP! Current HP: {self.hp}/{self.max_hp}") + + def receive_damage(self, damage): + # 计算伤害并减去防御力,更新 HP + if not isinstance(damage, int): + damage = int(damage) + + damage -= self.defense + if damage <= 0: + print(f"{self.name}'s defense absorbed the attack!") + return + + self.hp -= damage + print( + f"{self.name} received {damage} damage! Remaining HP: {self.hp}/{self.max_hp}" + ) + if self.hp <= 0: + self.alive = False + print(f"{self.name} has fainted!") + + def evade_damage(self) -> bool: + # 判断是否成功躲避敌方属性伤害,躲避成功为True + return randint(1, 100) <= self.evade + + + def cause_damage(self, opponent:"Pokemon"): + # 判断自己是否对敌方造成属性伤害,造成属性伤害为True + return not opponent.evade_damage() + + def add_status_effect(self, effect: Effect): + # 添加状态效果 + self.statuses.append(effect) + + def apply_status_effect(self): + # 应用所有当前的状态效果,并移除持续时间结束的效果 + for status in self.statuses[:]: # 使用切片防止列表在遍历时被修改 + status.apply(self) + status.decrease_duration() + if status.duration <= 0: + print(f"{self.name}'s {status.name} effect has worn off.") + self.statuses.remove(status) + + def type_effectiveness(self, opponent: Pokemon): + # 计算属性克制的抽象方法,具体实现由子类提供 + raise NotImplementedError + + def begin(self): + # 新回合开始时触发的方法,print("A new round begins......") + pass + + + def __str__(self) -> str: + return f"{self.name} type: {self.type}" + + +# GrassPokemon 类 +class GrassPokemon(Pokemon): + type = "Grass" + + def type_effectiveness(self, opponent: Pokemon): + # 针对敌方 Pokemon 的类型,调整效果倍率 + effectiveness = 1.0 + opponent_type = opponent.type + + if opponent_type == "Water": + effectiveness = 2.0 + elif opponent_type == "Fire": + effectiveness = 0.5 + return effectiveness + + def begin(self): + # 每个回合开始时执行草属性特性 + self.grass_attribute() + + def grass_attribute(self): + # 草属性特性:每回合恢复最大 HP 的 10% + amount = self.max_hp * 0.1 + self.hp += amount + if self.hp > self.max_hp: + self.hp = self.max_hp + print( + f"{self.name} heals {amount} HP at the start of the turn! Current HP: {self.hp}/{self.max_hp}" + ) + + +class FirePokemon(Pokemon): + type = "Fire" + def begin(self): + # 每个回合开始时执行火属性特性 + self.fire_attribute() + + def type_effectiveness(self, opponent: Pokemon): + # 针对敌方 Pokemon 的类型,调整效果倍率 + effectiveness = 1.0 + opponent_type = opponent.type + if opponent_type == "Glass": + effectiveness = 2.0 + elif opponent_type == "Water": + effectiveness = 0.5 + return effectiveness + + def fire_attribute(self): + #火属性特性,每次造成伤害,叠加10%攻击力,最多4层 + + if self.cause_damage(play.play1.current_computer_pokemon): + max_attack=self.attack*(1+10/100)**2 + while self.attack<=max_attack: + self.attack*=(1+10/100) + + + + + + +# Bulbasaur 类,继承自 GlassPokemon +class Bulbasaur(GrassPokemon): + name = "Bulbasaur" + + def __init__(self, hp=100, attack=50, defense=10 , evade=10) -> None: + # 初始化 Bulbasaur 的属性 + super().__init__(hp, attack, defense,evade) + + def initialize_skills(self): + # 初始化技能,具体技能是 SeedBomb 和 ParasiticSeeds + return [skills.SeedBomb(damage=60), skills.ParasiticSeeds(amount=10)] + + +# Charmande 类,继承自 GlassPokemon +class Charmander(FirePokemon): + name = "Charmander" + def __init__(self, hp=80, attack=35, defense=15, evade=10) -> None: + # 初始化 Bulbasaur 的属性 + super().__init__(hp, attack, defense , evade) + + def initialize_skills(self): + # 初始化技能,具体技能是 Ember 和 Flamecharge + return [skills.Ember(damage=10), skills.Flamecharge(damage=10)] diff --git a/tasks/task1/submit/test1/pokemon_game/skills.py b/tasks/task1/submit/test1/pokemon_game/skills.py new file mode 100644 index 0000000..d4d7930 --- /dev/null +++ b/tasks/task1/submit/test1/pokemon_game/skills.py @@ -0,0 +1,143 @@ +import random +from typing import TYPE_CHECKING +import effects + +if TYPE_CHECKING: + from pokemon import Pokemon + +1 +class Skill: + name: str + + def __init__(self) -> None: + pass + + def execute(self, user: "Pokemon", opponent: "Pokemon"): + raise NotImplementedError + + + + + + def __str__(self) -> str: + return f"{self.name}" + + +class SeedBomb(Skill): + name = "Seed Bomb" + + def __init__(self, damage: int, activation_chance: int = 15) -> None: + super().__init__() + self.damage = damage + self.activation_chance = activation_chance # 确保激活几率被正确初始化 + + def execute(self, user: "Pokemon", opponent: "Pokemon") -> None: + + # 判断是否造成伤害 + if opponent.evade_damage(): + print( + f"{user.name} used {self.name}, but {opponent.name} dodged this damage.This attack did not cause any damage." + ) + else: + opponent.receive_damage(self.damage) + print( + f"{user.name} used {self.name}, dealing {self.damage} damage to {opponent.name}" + ) + + # 判断是否触发状态效果 + if random.randint(1, 100) <= self.activation_chance: + opponent.add_status_effect(effects.PoisonEffect()) + print(f"{opponent.name} is poisoned by {self.name}!") + else: + print(f"{self.name} did not poison {opponent.name} this time.") + + + + +class ParasiticSeeds(Skill): + name = "Parasitic Seeds" + + def __init__(self, amount: int) -> None: + super().__init__() + self.amount = amount + + def execute(self, user: "Pokemon", opponent: "Pokemon") -> None: + # 给使用者添加治疗效果 + user.add_status_effect(effects.HealEffect(self.amount)) + print(f"{user.name} heals {self.amount} HP with {self.name}") + + # 给对手添加中毒效果 + opponent.add_status_effect(effects.PoisonEffect()) + print(f"{opponent.name} is poisoned by {self.name}!") + +'''**火花 (Ember):**小火龙发射出一团小火焰,对敌人造成 100% 火属性伤害,并有10%的几率使目标陷入“烧伤”状态(每回合受到10额外伤害, 持续2回合) +''' +class Ember(Skill): + name = "Ember" + + def __init__(self, damage:int,activation_chance: int = 10) -> None: + super().__init__() + self.damage = damage + self.activation_chance=activation_chance + + def execute(self, user: "Pokemon", opponent: "Pokemon") -> None: + # 判断是否造成伤害 + if opponent.evade_damage(): + print( + f"{user.name} used {self.name}, but {opponent.name} dodged this damage.This attack did not cause any damage." + ) + else: + opponent.receive_damage(self.damage) + print( + f"{user.name} used {self.name}, dealing {self.damage} damage to {opponent.name}" + ) + + # 判断是否触发状态效果 + if random.randint(1, 100) <= self.activation_chance: + opponent.add_status_effect(effects.BurnEffect()) + print(f"{opponent.name} is burned by {self.name}!") + else: + print(f"{self.name} did not burn {opponent.name} this time.") + + +class Flamecharge(Skill): + name = "Flame Charge" + is_charging = True # 标记是否正在蓄能 + '''蓄能爆炎 (Flame Charge ):**小火龙召唤出强大的火焰,对敌人造成 300% 火属性伤害,并有80%的几率使敌人陷入“烧伤”状态, + 这个技能需要1个回合的蓄力,并且在面对该技能时敌方闪避率增加 20%''' + def __init__(self, damage: int, activation_chance: int = 80,opponent_dodge_rate : int = 20) -> None: + + super().__init__() + self.damage = damage + self.activation_chance = activation_chance + self.opponent_dodge_rate = opponent_dodge_rate + + + def execute(self, user: "Pokemon", opponent: "Pokemon",play:"Play") -> None: + # 造成伤害 + last_exe_turn=0 #记录最近一次使用该技能的游戏轮次 + if play.turn - last_exe_turn >= 2: + self.is_charging = False + + if self.is_charging: + print("Charmander is charging for Flame Charge...") + + else: + opponent.evade+=self.opponent_dodge_rate + + if opponent.evade_damage(user, opponent): + print( + f"{user.name} used {self.name}, but {opponent.name} dodged this damage.This attack did not cause any damage." + ) + else: + opponent.receive_damage(self.damage) + print( + f"{user.name} used {self.name}, dealing {self.damage} damage to {opponent.name}" + ) + + # 判断是否触发状态效果 + if random.randint(1, 100) <= self.activation_chance: + opponent.add_status_effect(effects.BurnEffect()) + print(f"{opponent.name} is burned by {self.name}!") + last_exe_turn=play.turn #更新最近一次使用该技能的游戏轮次 + self.is_charging = True # 重新开始蓄能 diff --git a/tasks/task1/submit_tast1.keep b/tasks/task1/submit_tast1.keep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tasks/task1/submit_tast1.keep @@ -0,0 +1 @@ +