Python 知识

VS Code

代码自动对齐快捷键:Shift + Alt + F
快速编译/运行:Ctrl + F5
一键注释:Ctrl + K + C
一键取消注释:Ctrl + K + U

LeetCode

版本
在这里插入图片描述

Python

关于类,我的一点理解

一、类名不加括号

class Cat:
    def identify(self, name, age):
        self.name=name
        self.age=age

# 方式一
cat = Cat()
cat.identify("Tom",18)
# 方式二
cat.name = "Tom"
cat.age = 18
print(cat.name,cat.age)

output: Tom 18

s e l f self self 相当于类本身,下面两种方式都能给类赋值,并成功打印

二、类名加括号,必须要有__ i n i t init init__函数(主函数)

class Cat(object):
    def __init__(self, name, age): # 构造函数
        self.name = name
        self.age = age


cat = Cat("Tom", 18)
print(cat.name)

output: Tom 18

这种方法的类后面的括号内要加 O b j e c t Object Object,但 c a t cat cat 变量可以直接赋值

三、继承,子类括号中是父类

class 动物:
    def __init__(self, types, name):  # 构造函数
        self.types = types
        self.name = name

    def printType(self):
        print(self.types)

    def printName(self):
        print(self.name)


class(动物):
    def printName(self):  # 继承并修改
        pass


stuff =("橘猫", "小橘")
stuff.printType()
stuff.printName()

output: 橘猫
关于列表的解包(元组同理)
demo = [1, 2, 3, 4, 5]
print(demo)
print(*demo)

output: 
[1, 2, 3, 4, 5]
1 2 3 4 5
关于列表的枚举(元组同理)
demo = list("5x-2y=3")
for i, item in enumerate(demo):
    print(i, item)

output: 
0 5
1 x
2 -
3 2
4 y
5 =
6 3
关于装饰器,我的一些理解

一、正常写法(希望增强hello()函数的功能,但不改变其原本定义)

def makeitalic(fun): # 函数传参直接传入函数名,不用加括号
    def wrapped():
        return "<i>" + fun() + "</i>"
    return wrapped

def hello():
    return "hello world"

hello = makeitalic(hello) # 函数重定义
print(hello())
print(hello.__name__) # hello函数任存在,但指向 wrapped函数

output: 
<i>hello world</i>
wrapped

二、装饰器写法(同样需求,利用语法糖代替)

def makeitalic(fun):
    def wrapped():
        return "<i>" + fun() + "</i>"
    return wrapped

@makeitalic # 语法糖
def hello():
    return "hello world"

print(hello())
print(hello.__name__)

output: # 结果相同
<i>hello world</i>
wrapped

详细参考python中装饰器详解

Python函数式编程(把函数作为参数传入)【包含匿名函数、装饰器等】

python的新特性函数注释(定义函数时使用“:”及“ ->”符号)

global和nonlocal的作用(前者针对全局变量、后者针对函数内变量)

Python-collections模块

python中heapq堆的讲解

三元操作符:temp = x if x<y else y

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值