霍格沃兹测试开发 ceshiren.com
| 内置装饰器 | 含义 | 
|---|---|
| classmethod | 类方法 | 
| staticmethod | 静态方法 | 
定义:
调用:
# 1. 定义
class MethodsDemo:
    param_a = 0 #类变量
    def normal_demo(self): # 定义一个类方法,第一个参数必须为self
        """
        普通方法
        :return:
        """
        print("这是一个普通方法", self.param_a)
# 2. 调用
md = MethodsDemo()
md.normal_demo()
            # 1. 类的定义
class MethodsDemo:
    param_a = 0
    # 定义类方法必须加 classmethod装饰器
    @classmethod
    def classmethod_demo(cls):
        """
        类方法,第一个参数需要改为cls
        :return:
        """
        print("类方法", cls.param_a)
# 2. 类的调用
MethodsDemo.classmethod_demo() # 无需实例化,直接调用
            class DateFormat:
    def __init__(self, year=0, month=0, day=0):
        self.year = year
        self.month = month
        self.day = day
    def out_date(self):
        return f"输入的时间为{self.year}年,{self.month}月,{self.day}日"
   
year, month, day = 2017, 7, 1
demo = DateFormat(year, month, day)
print(demo.out_date())  
            输入的时间为2021年,12月,21日 这种格式# 1. 定义
class MethodsDemo:
    param_a = 0
    @staticmethod
    def static_demo():
        """
        静态方法
        :return:
        """
        print("静态方法") # 无法直接调用类变量
# 2. 调用
MethodsDemo.static_demo()
            # static 使用场景
class HeroFactory:
    # staticmethod 使用场景,
    # 方法所有涉及到的逻辑都没有使用实例方法或者实例变量的时候
    # 伪代码
    @staticmethod
    def create_hero(hero):
        if hero == "ez":
            return EZ()
        elif hero == "jinx":
            return Jinx()
        elif hero == "timo":
            return Timo()
        else:
            raise Exception("此英雄不在英雄工厂当中")
            | 名称 | 定义 | 调用 | 关键字 | 使用场景 | 
|---|---|---|---|---|
| 普通方法 | 至少需要一个参数 self | 实例名.方法名() | 无 | 方法内部涉及到实例对象属性的操作 | 
| 类方法 | 至少需要一个 cls 参数 | 类名.方法名() 或者实例名.方法名() | @classmethod | 如果需要对类属性,即静态变量进行限制性操作 | 
| 静态方法 | 无默认参数 | 类名.方法名() 或者实例名.方法名() | @staticmethod | 无需类或实例参与 | 
@property 之后方法就变成了属性@property 之后方法就变成了属性class DecoratorProperty:
    # 加了 `@property` 之后方法就变成了属性,
    @property
    def method_with_property(self):
        return 15
    def method_without_property(self):
        return 15
#使用属性一样调用(调用的时候不需要加(), 加了() 会报错)
print(DecoratorProperty().method_with_property)
print(DecoratorProperty().method_without_property())
            class DecoratorProperty:
    def __init__(self):
        self._image = 1
        self._label = 2
    @property
    def image(self):
        # 方法加入@property后,这个方法相当于一个属性,这个属性可以让用户进行使用,而且用户有没办法随意修改。
        return self._image
    @property
    def label(self):
        return self._label
dec = DecoratorProperty()
print(dec.image)
print(dec.label)
            #  无类型注解
def greeting(name) :
    return 'Hello ' + name
#  有类型注解
def greeting(name: str) -> str:
    return 'Hello ' + name
            
Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]
# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
            格式:
注意:
pip install pyyaml当前学员的姓名为XXX, 当前学员的学校为XXX, 专业为xxxpython 解释器对模块位置的搜索顺序是:
try:
    可能产生异常的代码块
except [ (Error1, Error2, ... ) [as e] ]:
    处理异常的代码块1
except [ (Error3, Error4, ... ) [as e] ]:
    处理异常的代码块2
except  [Exception]:
    处理其它异常
            try:
    result = 20 / int(input('请输入除数:'))
    print(result)
except ValueError:
    print('必须输入整数')
except ArithmeticError:
    print('算术错误,除数不能为 0')
else:
    print('没有出现异常')
print("继续执行")
            try:
    a = int(input("请输入 a 的值:"))
    print(20/a)
except:
    print("发生异常!")
else:
    print("未发生异常")
finally :
    print("执行 finally 块中的代码")
            raise 异常名(提示信息)def set_age(num):
    if num<=0 or num >120:
        raise ValueError(f"值错误:  {num}")
    else:
        print(f"设置的年龄为:{num}")
set_age(-1)
            
class MyError(Exception):
    def __init__(self, value ):
        self.value = value
def set_age(num):
    if num<=0 or num >120:
        raise MyError(f"值错误:  {num}")
    else:
        print(f"设置的年龄为:{num}")
set_age(-1)