认识Python 推荐学习视频传送门:求知讲堂2020python+人工智能 99天完整版
环境与解释器 IDE 里如果报下面这类错误:
Cannot set up a python SDK at Python 3.7 ... The SDK seems invalid
优先排查这几项:
1、当前配置的 python.exe 路径是不是已经失效
2、Anaconda 或虚拟环境是不是被移动、删除、重装过
3、IDE 里的解释器是不是选到了错误的 base 环境
4、删掉当前解释器配置后,重新指定一次真实存在的 python.exe
这类问题本质上通常不是代码问题,而是解释器路径、环境元数据或者 IDE 缓存不一致。
第一个main函数 1 2 3 4 5 def print_hi (name ): print (f'Hi, {name} ' ) if __name__ == '__main__' : print_hi('PyCharm' )
输出打印 ptint打印 1 2 3 4 5 6 7 8 9 10 rs = 123 print ('rs={}' .format (rs))print ('rs={0}' .format (rs))sum_func = lambda x,y,z,c: x*y*z*c rs1 = sum_func(4 ,5 ,6 ,7 ) print ('rs1 = %d' %rs1)print ('rs1 = %d,study %s' %(rs1, 'Python' ))
logging日志 1 2 3 4 5 6 7 8 9 10 11 12 import loggingimport sysLOG_FORMAT = "[%(asctime)s %(levelname)1.4s] %(message)s" logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format =LOG_FORMAT) name = 'hello world' print ("%s study Python!" % name)print ("{} study Python! And realy age is {}" .format (name, 20 ))logging.info("%s study Python!" , name)
排查异常时,日志最好把堆栈也带出来,不然很多问题只能看到一句报错文本:
1 2 3 4 try : run_task() except Exception: logging.exception("执行任务异常" )
logging.exception(...) 会自动打印当前异常堆栈,定位问题比手写一行普通日志更直接。
获取当前时间的用法 1 2 3 4 5 6 7 8 9 10 11 1. 先导入库:import datetime2. 获取当前日期和时间:now_time = datetime.datetime.now()3. 格式化成我们想要的日期:strftime()比如:“2016 -09-21 ”:datetime.datetime.now().strftime('%Y-%m-%d' ) 4. 在当前时间增加1 小时:add_hour=datetime.datetime.now()+datetime.timedelta(hours=1 ) 格式“小时”:now_hour=add_hour.strftime('%H' ) 5. 时间的三种存在方式:时间对象,时间字符串,时间戳。
具体可以参考python获取当前时间的用法
异常-Exception 初识 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import loggingimport sysLOG_FORMAT = "[%(asctime)s %(levelname)1.4s] %(message)s" logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format =LOG_FORMAT) try : i = 1 / 0 except Exception as e: logging.error('运算时异常' , e) finally : logging.info('异常学习' ) print (dir (Exception))
自定义异常 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import loggingimport sysLOG_FORMAT = "[%(asctime)s %(levelname)1.4s] %(message)s" logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format =LOG_FORMAT) class TooLongMyException (Exception ): def __init__ (self, len ): self.len = len def __str__ (self ): return '您输入的姓名数据长度是' + str (self.len ) + '超过了长度' input = input ()try : if len (input ) > 5 : raise TooLongMyException(len (input )) else : print ('您输入的数据为:' + input ) except TooLongMyException as e: logging.error('捕获自定义异常啦' , e) pass
结果输出:
1 2 3 4 5 6 7 8 dfsdss --- Logging error --- Traceback (most recent call last): File "/Users/Lauy/mine/study_python/exception/自定义异常.py" , line 20 , in <module> raise TooLongMyException(len (input )) TooLongMyException: 您输入的姓名数据长度是6 超过了长度 During handling of the above exception, another exception occurred:
函数 匿名函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 result = lambda a, b, c: a * b * c print (result(12 , 34 , 2 ))age = 15 print ('每天学习' if age > 18 else '偶尔学习' )funcTest = lambda x, y: x if x > y else y print (funcTest(2 , 12 ))rs = (lambda x, y: x if x > y else y)(16 , 12 ) print (rs)rs1 = lambda x: (x ** 2 ) + 890 print (rs1(10 ))
递归函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 def recursion_calculation (count ): if count == 1 : return 1 else : return count * recursion_calculation(count - 1 ) print ('最终结果为:%d\n' %recursion_calculation(5 ))import osdef find_path_file (path ): list_file = os.listdir(path) for file_item in list_file: complete_path = os.path.join(path, file_item) if os.path.isdir(complete_path): print ("文件夹名:" + complete_path) find_path_file(complete_path) else : print ('文件名:\t' + file_item) find_path_file('/Users/Lauy/Desktop/temp' )
类 创建一个类对象 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 ''' 类: ''' import loggingimport sysclass Person : username = 'hello world' def __init__ (self ): self.age = 20 def study (self, name=username ): print ("%s study Python!" % name) print ("{} study Python! And realy age is {}" .format (name, 20 )) def __str__ (self ): return 'username=' + self.username + ',age=' + str (self.age) ''' 创建一个对象 ------ 两者打印出来的内存地址都一样的 --- 4381304016 ... 18 ===================> <class 'int'> 4381304016 ... 20 ''' obj = Person() print (type (obj.age))print (id (obj.age))obj.age = 18 print (id (obj.username))obj.tag = '标签' print (id (obj.tag))print (obj.age)print ("===================>" )print (obj.__str__())print ("===================>" )obj1 = Person() print (type (obj1.age))print (id (obj1.age))print (id (obj1.username))obj1.tag = '标签' print (id (obj1.tag))print (obj1.age)
类属性和实例属性 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 import random''' 1、可以被类对象和实例对象共同访问使用 2、类属性属于类所有,所有对象共享一份内存地址 3、实例属性只能由实例对象访问使用 4、修改类属性值需要用类 Class.类属性=值,如果是 obj.类属性值,结果只是新增实例属性 ''' class Person : id = random.randrange(1 , 100 , 10 ) def __init__ (self, weight ): self.username = 'hello world' self.age = 20 self.weight = weight def study (self ): print ("study Python!" ) ''' 创建一个对象 每创建一个对象都要添加属性,显然很费事,所以我们可以采用上述的 __init__方法定义实例属性,在类实例化时就被执行 ''' obj = Person(110 ) obj.gender = 'Male' print ('obj.username:%s' %obj.username)print ('obj中:类属性id为%d,username is %s, __weight is %d' %(obj.id , obj.username, obj.weight))obj.id = 'i change id value' print ('obj中:类属性id为%s,username is %s, __weight is %d' %(obj.id , obj.username, obj.weight))obj = Person(120 ) print ('obj中:类属性id为%d,username is %s, __weight is %d' %(obj.id , obj.username, obj.weight))print ('类属性id为%d' %Person.id )
类方法和静态方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 import uuid''' 静态方法主要来存放逻辑性的代码,本身和类已经实例对象多有交互,相当于 static final field 类方法属于类所有,相当于 static method ''' class Student : stu_name = uuid.uuid4() @classmethod def study (cls ): return str (cls.stu_name) + '正在学习~' print (Student.study())import timeclass TimeUtil : @staticmethod def get_current_time (): return time.strftime('%Y:%M:%D' ) print (TimeUtil.get_current_time())
init方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 class Person : def __init__ (self, weight ): self.username = 'hello world' print ('username address is %s' %id (self.username)) self.age = 20 self.weight = weight def study (self ): print ("study Python!" ) ''' 创建一个对象 每创建一个对象都要添加属性,显然很费事,所以我们可以采用上述的 __init__方法定义实例属性,在类实例化时就被执行 ''' obj = Person(110 ) obj.gender = 'Male' obj.height = 1.8 print (obj.username, obj.age, obj.gender, obj.height, obj.weight)obj1 = Person(120 ) obj1.gender = 'Fmale' obj1.height = 1.8 print (obj1.username, obj1.age, obj1.gender, obj1.height, obj1.weight)
new实例化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 ''' __new__中:请使用父类的new方法,不要使用对象本身的new方法,容易造成深度递归 子类重写了父类的方法,所以只输出子类的方法了 ''' class Person : def __init__ (self, weight ): self.__weight = weight print ('Person对象初始化方法,我会后执行' ) def __new__ (cls, *args, **kwargs ): print ('Person对象new方法,我会先执行' ) return object .__new__(cls) class Male (Person ): def __init__ (self ): print ('Male对象初始化方法,我会后执行' ) def __new__ (cls, *args, **kwargs ): print ('Male对象new方法,我会先执行' ) return object .__new__(cls) ''' Person对象new方法,我会先执行 Person对象初始化方法,我会后执行 ================ 【子类重写了父类的方法,所以只输出子类的方法了】 Male对象new方法,我会先执行 Male对象初始化方法,我会后执行 ''' p = Person(105 ) print ("================" )m = Male()
熟知self 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ''' 特点: self只有在类中定义实例方法的时候才有意义,在调用时候不必传入相应的参数,而是由解释器自动去解析、指向 self的名字是可以更改的,只是默认约定如此 self指的是类实例对象本身,相当于Java的this指向当前对象 ''' class People : name = 'hello world' def get_self (self ): print ('name is %s, address is %s' %('getSelf' , self)) return self peo = People() print (peo.get_self())print (peo)print (id (peo) == id (peo.get_self()))
slot属性限制 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 ''' 作用: 1、限制要添加的实例属性 2、节省内存空间 ''' class Student : __slots__ = ('name' , 'age' , '__dict__' ) def __str__ (self ): return '{}...{}' .format (self.name, self.age) stu = Student() stu.name = 'hello world' stu.age = 18 print (stu)print (stu.__dict__)''' 在继承关系中的使用:__slots 子类未声明 __slots__时,那么是不会继承父类的__slots,此时子类是可以随意的属性添加与赋值 子类声明 __slots__时,继承父类的 __slots__,也就是子类__slots__的范围是 其自身 ''' class MaleStudent : __slots__ = ('name' , 'height' , 'age' ) pass m = MaleStudent() m.name = 'study Python' m.age = 20 m.height = 1.8 print (m.name, m.age)
函数属性property 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 import random''' 函数属性: 1、通过property方法直接访问私有属性 - 本来__weight是类私有属性,然后通过property后可以直接访问,但是还是会经过定义的get_weight和set_weight方法 2、通过装饰器修饰[注解] - @property 装饰器修饰,提供一个get方法 - @age.setter 提供age字段的set方法 - @age注解的字段名和函数名需要匹配 ''' class Person : def __init__ (self, weight ): self.username = 'hello world' self.__age = 20 self.__weight = weight def set_weight (self, weight ): self.__weight = weight def get_weight (self ): return self.__weight @property def age (self ): return self.__age @age.setter def age (self, age ): self.__age = age weight = property (get_weight, set_weight) obj = Person(110 ) print (obj.get_weight())obj.weight = 10 print (obj.get_weight())obj.set_weight(23 ) print (obj.weight)print (obj.age)obj.age = 18 print (obj.age)
动态绑定属性 / 类方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 ''' 动态绑定属性 / 类方法 ''' import typesimport uuiddef study (slef ): print ('我喜欢学习Python!' ) @classmethod def play (cls ): print ('我喜欢玩' ) class Person : pass p = Person() p.study = types.MethodType(study, p) p.study() Person.play = play Person.play() Person.id = uuid.uuid1() print (Person.id )
单继承 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ''' 单继承: 默认继承超类,object ''' class Animal (object ): def eat (self ): print ('干饭了' ) def sing (self ): print ('唱歌了' ) class dog (Animal ): def eat (self ): print ('啃骨头' ) class cat (Animal ): def eat (self ): print ('偷鱼吃' ) dog = dog() dog.eat()
多继承 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 ''' 多继承 ''' class D : def eat (self ): print ('爸爸叫吃饭了' ) class C (D ): def eat (self ): print ('C儿子在吃饭' ) def play (self ): print ('C儿子吃完饭,还能快乐玩耍' ) class B (D ): def eat (self ): print ('B儿子在吃饭' ) class A (B, C): pass ''' 广度优先遍历: 1、在执行eat方法时,会先找本对象a中是否包含,如果没有就向上查找B,如果B中有eat方法就返回。如果没有,就再去找父亲C,找到返回。 2、同理向上查找,直至超类object。没有就报错了【'A' object has no attribute 'eat1'】 ''' a = A() a.eat() a.play()
多态 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ''' 多态条件 1、继承 2、子类重写父类方法 ''' ''' 单继承: 默认继承超类,object ''' class Animal (object ): def eat (self ): print ('干饭了' ) @staticmethod def commonStaticSonClassMethod (obj ): obj.eat() class dog (Animal ): def eat (self ): print ('啃骨头' ) class cat (Animal ): def eat (self ): print ('偷鱼吃' ) class_list = [dog(), cat()] for item_class in class_list: Animal.commonStaticSonClassMethod(item_class)
私有化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 import random''' 私有化属性: 1、私有化的 实例属性,不能再被外部直接访问,可以在本类中使用修改 2、在属性名前加 __ 就可以变成私有化了 ''' class Person : id = random.randrange(1 , 100 , 10 ) tag_ = '后面单下划线,避免属性名与Python关键字冲突' def __init__ (self, weight ): self.username = 'hello world' self.age = 20 self.__weight = weight def __set_id (self ): self.id = '我是私有化方法' return self.id def _protected_method (self ): print ('我是受保护的方法' ) def __magic__ (self ): print ('魔法方法,一般是Python自有的' ) def get_person (self ): print ('我在对象内部先调用了:' + self.__set_id()) return '{}的年龄是{},体重{}' .format (self.username, self.age, self.__weight) obj = Person(110 ) print (obj.get_person())
注意:
单例模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ''' 单例模式 ''' class Person : def __init__ (self ): pass def __new__ (cls, *args, **kwargs ): if not hasattr (cls, '_instance' ): cls._instance = object .__new__(cls) return cls._instance p1 = Person() p2 = Person() print (id (p1))print (id (p2))
内置类方法 析构方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Animal : def __init__ (self, name ): self.name = name print ('这是构造初始化方法' ) ''' 析构方法: 主要的应用就是来操作对象的释放,一旦释放完毕,对象便不能再使用 当在某个作用域下面,没有被使用[引用]的情况下,解析器会自动的调用此函数,来释放此对象所占的内存空间 ''' def __del__ (self ): print ('%s 这个对象被彻底清理了,内存空间也释放了' %self.name) dog = Animal('哈士奇' ) print (dog.name)input ('程序等待中,请输入......' )''' 输出示例: 这是构造初始化方法 哈士奇 程序等待中,请输入......1 哈士奇 这个对象被彻底清理了,内存空间也释放了 '''
数据库操作 MySQL 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 from pymysql import *connection = connect(host='127.0.0.1' , user='root' , password='root' , database='blue' , charset='utf-8' , autocommit=False ) try : cursor = connection.cursor() insert_sql = ''' INSERT INTO tb_student(username, grade) values ('Lauy', '二年级') ''' cursor.execute(insert_sql) connection.commit() cursor.execute('SELECT * FROM tb_student' ) result = cursor.fetchall() print (cursor.rowcount) cursor.close() connection.close() for student in result: print (student) except Exception as e: print (e)