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的作用(前者针对全局变量、后者针对函数内变量)
三元操作符:temp = x if x<y else y