为了不让自己再次陷入半途而废的境地,我想采取快速学习快速实践的策略:
1.速览全局语法;2.速练语法;3.快速项目实战
一、速览全局语法
学习推荐网站:https://learnxinyminutes.com/
我目前就是直接用它学习,有不懂的地方直接问豆包整理思路。
下面是自己学习整理的笔记供大家参考:
1.语法问题
- 输入问题
name = "python" # 外层双引号,内层单引号 print(f"i'm {name}, end='!'")
**参数名作用:收集所有多余的关键字参数,自动封装成字典
参数名 → 字典的 key
参数值 → 字典的 value
- 一等对象
可以赋值给变量 、可以作为参数传递 、可以作为函数返回值、可以在容器(列表 / 字典)中存放
map(函数, 可迭代对象)作用:依次把可迭代对象里的每一个元素,传入指定函数执行,最终返回一个迭代器。
规则:
第一个参数:必须是可调用对象;
第二个参数:列表、元组等可迭代序列;
逐个遍历序列元素,执行
函数(元素),收集所有结果。按位置成对取值 ,依次把同下标的元素传给函数;
遍历次数 = 最短的那个可迭代对象的长度;
- 匿名函数
python"""使用规则: 只能有一个表达式,不能写代码块、if/for/while、多行语句; 表达式的运算结果自动作为返回值,不需要写 return;""" lambda x: x > 5 # 参数:x # 表达式:x > 5 # 自动返回表达式结果(布尔值)识别
lambda关键字 → 判定为小型函数定义;解析参数列表、单行表达式;
在内存中创建一个 function 对象 (和
def创建的对象结构一致);因为没有函数名,不会注册到全局 / 局部命名空间,仅临时存在。
- filter函数
filter(判断函数, 可迭代对象):过滤元素 ,只保留让判断函数返回True的元素。
- dir函数
dir()是 Python 内置函数,读取对象的命名空间属性集合 ,把对象所有可用属性、方法、常量整理成列表返回;对模块math调用,就是遍历模块对象的内部成员。
- 主程序标识
每个 Python 模块运行时,解释器都会自动给它内置一个
__name__变量;当前文件是「入口主程序」时,__name__固定等于字符串'__main__',被别人导入时则等于模块名。
- 魔法方法
__init__、__new__、__str__这类前后双下划线 的方法,叫魔法方法(特殊方法):是 Python 解释器预留的系统内置接口;
名字由语言官方固定,用来对接解释器底层逻辑;
你只能重写覆盖它的内部逻辑,不能修改它的名字。
- super()含义
super().init(name):
super()会拿到当前类的父类 ,再调用父类的__init__构造方法;作用是子类重写构造方法后,主动执行父类原本的初始化逻辑。
- 继承实现
class Superhero(Human),就建立继承关联 :Superhero是子类,Human是它的基类(直接父类)。
python# 使用规则: class 子类名(父类1, 父类2, ...): 类体代码使用案例:
python# 父类 class Human: species = "H. sapiens" def __init__(self, name): self.name = name # 子类:继承 Human class Superhero(Human): species = 'Superhuman' # 测试 s = Superhero("Tom") print(s.name) # 继承来的实例属性 print(s.species) # 子类重写的类属性
2.常见报错
2.1 max is <map object at 0x000001547D69C0A0>
原因:
直接打印了 map 对象本身 ,而非遍历取值,map 默认返回迭代器对象,不会直接展示数据。
解决:
- 转换成列表:用list包裹,一次性取出所有元素。
python
res = map(max, [1,2,3], [4,2,1])
print(list(res)) # [4, 2, 3]
- for循环遍历:逐个取出元素
python
res = map(max, [1,2,3], [4,2,1])
for item in res:
print(item)
- 解包打印:
python
res = map(max, [1,2,3], [4,2,1])
print(*res) # 4 2 3
2.2 NameError: name 'ceil' is not defined
原因:
ceil 属于 math 模块,你只导入了 math,但没有正确调用 / 单独导入 ceil。
解决:
- 完整调用:调用时带上模块名
math.ceil
python
import math
print(math.ceil(math.sqrt(5)))
- 单独导入:单独导入ceil
python
from math import sqrt, ceil
print(ceil(sqrt(5)))
2.3 @age1.setter NameError: name 'age1' is not defined
原因:
@age1.setter 是 Python 属性装饰器(property 读写器),原因是在写 @age1.setter 之前,没有先用 @property 定义 age1 属性。
property 读写必须成对出现,顺序不能乱:
先用 @property 定义 读方法 (方法名 = 属性名 age1)
再用 @age1.setter 定义 写方法
python
class Person:
def __init__(self):
self._age = 0
# 第一步:定义 property 读属性 age1
@property
def age1(self):
return self._age
# 第二步:再写 age1.setter,此时 age1 才存在
@age1.setter
def age1(self, value):
# 可以加校验逻辑
if isinstance(value, int) and 0 < value < 150:
self._age = value
解决:
- 没有成对出现:直接写
@age1.setter,前面没有@property
python
class Person:
# 错误:age1 从未定义,直接使用 age1.setter
@age1.setter
def age1(self, value):
pass
名字不一致:setter 的装饰器名称 ,必须和上方@property的方法名完全一致
python
class Person:
@property
def age(self): # 名字是 age
return self._age
@age1.setter # 写成 age1,名字对不上 → 同样 NameError
def age1(self, value):
pass
2.4 i=man('llj') TypeError: man() takes no argument
原因:
man 这个函数 / 类,调用时传了参数,但它定义时不接收任何参数 。调用时传入了字符串 'llj',但 man 的定义里没有设置形参,参数数量不匹配,所以报错。
解决:
- 普通函数:错误写法,根据需求添加形参
python
# 接收一个参数 name
def man(name):
pass
i = man('llj') # 正常运行
- 错误调用_init_方法:类里没写
__init__,默认是空构造,不接收额外参数;在_init_方法里定义参数
python
class man:
# 构造方法,接收参数 name
def __init__(self, name):
self.name = name
def func(self):
print(self.name)
i = man('llj') # 正常
2.5 TypeError: Cannot create a consistent method resolution order (MRO) for bases
原因:
无法为父类 Man 和 child 生成合法、一致的方法解析顺序(MRO) 。本质是出现了循环继承 / 继承顺序冲突,Python 解析继承链时出现矛盾,拒绝创建子类。
解决:
- 继承次序错误:先继承直接父类,再继承 上级父类 ,顺序至关重要。MRO 链 逐个往后找类,否则无法精准控制执行哪一个父类;
python
class son(直接父类,上级父类)
- 循环继承错误:父子类互相继承,形成闭环,MRO 无法排序。只继承「最下层子类」
python
class Man:
pass
class child(Man):
pass
# 只继承 child,自动包含 Man 的所有内容
class son(child):
pass
3.代码实例
供大家参考一下,我速敲的代码
python
# 简单输入输出的使用
# name="python"
# print(f"i'm {name},what is your name", end='?')
# user=input("enter your name:")
# print(f"{user} welcome back!")
# enter=input("do you wanna begin?y/n:")
# print("let's begin!") if enter=="y" else print("then let's have a try!")
# 简单容器的使用
# list2=[1,2]
# list1=[3,4,5]
# tup=("dog","cat","horse")
# print("list is ",list2)
# number=input("enter a number to a list2:")
# list2.append(int(number))
# print("list2 is ",list2)
# list2.extend(list1)
# print("list2 is ",list2)
# list2.pop(5)
# print("list is ",list2)
# if list2.pop()>5:
# print("list2 is smaller than 5.")
# elif list2.pop()<5:
# print("list2 is smaller than 5.")
# else:
# print("list2 is equal to 5.")
# for animal in tup:
# print(f"{animal} is mammal")
# for i in range(5):
# print(i)
# for i in range(3,6):
# print(i)
# print("------------------------------------------------------------")
# obj={"one":1,"two":2,"three":3}
# for i in iter(obj):
# print(i)
#简单函数的使用
# def add(a,b):
# print("x is {} and y is {}".format(a,b))
# return a+b
# print("result is ",add(5,7))
# def allArgs(*args,**keywords):
# print(args)
# print(keywords)
# allArgs(1,2,one=1,two=2)
# def swap(x,y):
# return y,x
# print("swap:",swap(1,2))
# y=8
# def setY(n):
# y=n
# print("setY's y ",y)#改变只在函数内生效
# setY(3)
# print("y:",y)
# def setGlobalY(n):
# global y
# y=n
# print("setGlobalY's y ",y)
# setGlobalY(3)
# print("y:",y)
# #把内部函数当作返回值返回,完全符合一等函数特性。
# def adder(x):
# def inner(y):
# return x+y
# return inner
# adder1=adder(10)
# print("listadd is ",list(map(adder1,[1,2,3])))
# print("max is ",list(map(max,[1,2,3],[0,3,1])))
# print("filtered num is ",list(filter(lambda x:x>3,[2,3,4])))
#简单函数使用
# import math
# print(math.sqrt(5))
# print(math.ceil(math.sqrt(5)))
# print(math.floor(math.sqrt(5)))
# print("math:",dir(math))
# 简单类的定义和使用
class Man:
def __init__(self,name):#本质是调用构造方法,修改参数。
self.name = name
self.age = 0
def say(self,msg):
print(f"{self.name}:{msg}")
def sing(self):
return "i'm a man,and i'm singing!"
var="i'm a manvar"
@classmethod
def get_var(cls):
return cls.var
@staticmethod
def sta():
return "*sta*"
@property#getter
def get_age(self):
return self.age
@get_age.setter#这个地方的方法名要与@property里定义的函数名保持一致,相当于是getter对应的setter
def get_age(self,age1):
self.age = age1
@get_age.deleter#相当于是getter对应的deleter
def get_age(self):
del self.age
if __name__ == "__main__":
print("this is the main file")
i=Man('llj')
i.say('hello')
i.say(i.get_var())
Man.var="i'm a queen"
i.say(i.get_var())
print(Man.sta())
i.say(i.age)
i.age=24
i.say(i.age)
del i.age
#验证是否有该属性
print(dir(i))
print(i.__dict__)#打印自定义的方法
#类的继承
class child(Man):
var = "i'm a child"
c=child("children")#调用__init__构造方法
print(c.name)
print(c.var)
if isinstance(c,Man):#只有实例才可以用isinstance与类型进行匹配比较
print("I'm the child of Man!")
class son(child,Man):#继承的顺序很重要:直接父类,上级父类......
var = "i'm a son"
def __init__(self,name,haveRelate=True,relations=["Man","child"]):
self.relate=haveRelate
self.relations=relations
super().__init__(name)
def printRelate(self):
if self.relate:
print("this is my family,they are ")
for r in self.relations:
print(r)
s=son("son")
print(s.var)
s.printRelate()
4.小结
这个速学还是挺好玩的,感觉更有目的一点,后续学习我也会持续更新的,希望这次学习的旅程能够找到自己的方向,也希望对大家有帮助!