提交 86357d36 编写于 作者: 唐僧打怪兽's avatar 唐僧打怪兽

Python3基础Demo

上级 97e3a944
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
class Student(object):
pass
bart = Student()
print(bart)
bart.name='张三'
print(bart.name)
class Student(object):
"""docstring for Student"""
def __init__(self, name,score):
super(Student, self).__init__()
self.name=name
self.score=score
def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
bart = Student('李王',88)
print(bart.name)
print(bart.get_grade())
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
#实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问
#变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def set_score(self, score):
if 0 <= score <= 100:
self.__score = score
else:
raise ValueError('bad score')
bart = Student('黎明',98)
print(bart.print_score())
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 获取对象信息
#type()判断对象类型
print(type(123))
#判断函数 使用types模块中定义的常量
import types
def fn():
pass
b = type(fn) == types.FunctionType
print(b)
#对于class的继承关系来说,使用type()就很不方便。我们要判断class的类型,可以使用isinstance()函数。
import Extends
a = Extends.Animal()
d = Extends.Dog()
c = Extends.Cat()
print(isinstance(a,Extends.Animal))
print(isinstance(d,Extends.Dog))
print(isinstance(c,Extends.Cat))
#dir()获取对象所有方法属性
print(dir(a))
#仅仅把属性和方法列出来是不够的,配合getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态
class MyObject(object):
"""docstring for MyObject"""
def __init__(self, arg):
super(MyObject, self).__init__()
self.arg = arg
def power(self):
return self.arg * self.arg
obj = MyObject('aa')
b = hasattr(obj,'arg') #判断是否有属性 'arg'?
print(b)
setattr(obj,'arg',12)
print(getattr(obj,'arg'))
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 继承和多态
class Animal(object):
"""docstring for Animal"""
def run(self):
print('Animal is running')
class Dog(Animal):
def run(self):
print('Dog is running...')
def eat(self):
print('Dog eating meat...')
class Cat(Animal):
pass
dog = Dog()
dog.run()
cat = Cat()
cat.run()
dog.eat()
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# Python提供了切片(Slice)操作符
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print(L[0:3])
print(L[-2:])
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
#关键字lambda表示匿名函数,冒号前面的x表示函数参数
anonymous = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(anonymous)
\ No newline at end of file
a = 100
if a > 0:
print(a)
else:
print(-a)
#Python允许用'''...'''的格式表示多行内容
print('''line1
line2
line3''')
#变量
a = '我是变量'
print(a)
print(100 + 200 + 300)
#多个字符串是空格
print('多个字符串拼接','第二个字符串','第三个字符串')
print('100 + 200','=',100 + 200)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 调试
s = '0'
n = int(s)
print 10 / n
#启动Python的调试器pdb
#python -m pdb debug1.py
#如果要比较爽地设置断点、单步执行,就需要一个支持调试功能的IDE。目前比较好的Python IDE有PyCharm:
#http://www.jetbrains.com/pycharm/
#另外,Eclipse加上pydev插件也可以调试Python程序。
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 装饰器
def now():
print('2015-1-1')
f = now
print(f())
print(f.__name__)
#假设我们要增强now()函数的功能,比如,在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
@log
def now():
print('2015-1-1')
print(now())
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log('execute')
def now():
print('2015-1-1')
print(now())
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
print(log(now))
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
#dict
d={'Michale':95,'Tom':80,'Lee':99}
print(d)
print('Tom:',d['Tom'])
#key不存在情况
print('Tom' in d)
print('key not exist:',d.get('None'))
print('key not exist,print default val:',d.get('None',100))
#set
s = set([1,2,3])
print('set is:',s)
s.add(4)
print('set add element:',s)
s.remove(4)
print('set remove element:',s)
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 枚举
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
print(Month.Jan)
#如果需要更精确地控制枚举类型,可以从Enum派生出自定义类:
from enum import Enum,unique
@unique
class Weekday(Enum):
Sun = 0
Mon = 1
print(Weekday.Sun)
print(Weekday.Sun.value)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 错误处理
try:
print('try...')
r = 10/0
print('result:',r)
except ZeroDivisionError as e:
print('exception:',e)
finally:
print('finally')
print('END')
#如果没有错误发生,可以在except语句块后面加一个else,当没有错误发生时,会自动执行else语句
try:
print('try...')
r = 10 / int('2')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('no error!')
finally:
print('finally...')
print('END')
#记录错误
import logging
def foo(s):
return 10 / int(s)
def bar(s):
return foo(s) * 2
def main():
try:
bar('0')
except Exception as e:
logging.exception(e)
main()
print('END')
#抛出错误
class FooError(ValueError):
pass
def foo(s):
n = int(s)
if n==0:
raise FooError('invalid value: %s' % s)
return 10 / n
foo('0')
#raise语句如果不带参数,就会把当前错误原样抛出。此外,在except中raise一个Error,还可以把一种类型的错误转化成另一种类型
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
def is_odd(n):
return n % 2 == 1
filter1 = filter(is_odd,[1,2,3,4,5,6,7,8,9,10])
print(list(filter1))
def not_empty(s):
return s and s.strip()
filter2 = filter(not_empty,['A','','B','C','D','','','X','1'])
print(list(filter2))
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# for x in xx 表示循环
names=['张胜男','李强','Machial','李章','Tom']
for name in names:
print(name)
#0-100的整数序列
r = range(101)
lr = list(r)
sum = 0
for ll in lr:
sum += ll
print(sum)
#while
n = 200
sum1 = 0
while n > 100:
sum1 += n
n = n-1
print(sum1)
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
print('abs:',abs(-100))
print('max:',max(1,2,5,7,12,8))
print(int('123'))
print(int(12.34))
print(float('12.34'))
print(str(1.23))
print(str(100))
print(bool(1))
print(bool(''))
a = abs
print(a(-1))
#自定义函数
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError('bad operand type')
if x>0:
return x
else:
return -x
print('user define function my_abs:',my_abs(-12))
#print('user define function my_abs raise TypeError:',my_abs('a'))
#返回多个值
print('====返回多个值例子====')
import math
def move(x,y,step,angle = 0):
nx = x + step * math.cos(angle)
ny = y + step * math.sin(angle)
return nx,ny
print('表达式x, y = move(100, 100, 60, math.pi / 6)返回多个值','=',move(100, 100, 60, math.pi / 6))
r = move(100, 100, 60, math.pi / 6)
print('返回单一值:', r)
#
#*args是可变参数,args接收的是一个tuple;
#**kw是关键字参数,kw接收的是一个dict。
#
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
L = [x * x for x in range(10)]
print(L)
#只要把一个列表生成式的[]改成(),就创建了一个generator
g = (x * x for x in range(10))
for n in g:
print(n)
#一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
f = fib(10)
for n in f:
print(n)
print('hello world ')
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
age = 20
print('your age is',age)
if age >= 6:
print('teenager')
elif age > 18:
print('adult')
else:
print('kid')
s = input('input your age:')
birth = int(s)
if birth < 2000:
print('00前')
else:
print('00后')
\ No newline at end of file
name = input('please enter your name:')
print('user input:', name)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# IO
import os,json
f = open('D:/python/demo/basic.py','r',encoding='utf-8')
# r 只读
c = f.read()
print(c)
for line in f.readlines():
print(line.strip()) # 把末尾的'\n'删掉
# w 写
# f.write()
# f.close()
print('os name %s' % os.name) #nt:windows
print('os enveronment %s' % os.environ)
#JSON
d = dict(name='Bob', age=20, score=88)
print(json.dumps(d))
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str))
#{'age': 20, 'score': 88, 'name': 'Bob'}
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
#list iterator
d = ['1',2,'a','b']
for key in d:
print(key)
#dict
d1 = {'a':1,'b':2,'c':3}
#dict key
for key in d1:
print(key)
#dict values
for val in d1.values():
print(val)
#dict items
for k,v in d1.items():
print('k is %s,v is %s' % (k,v))
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
#list
classmates=['张三','李四','王五']
print(classmates)
print('classmates len:%d' % len(classmates))
#往list中追加元素到末尾
classmates.append('赵六')
print(classmates)
#往list中插入元素
classmates.insert(1,'大拿')
print(classmates)
#删除list末尾的元素
classmates.pop();
print(classmates)
classmates.pop(1)
print(classmates)
#list里面的元素的数据类型也可以不同
L=['a',1,True]
print(L)
LS=['list中套list',L,1]
print(LS)
#有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改
classmates1 = ('Michale','Tom','Lee')
print(classmates1)
#注意:tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。即指向'a',就不能改成指向'b',指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的!
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
lr = list(range(1,11))
print(lr)
lr1 = [x * x for x in range(1,20) if x % 2 == 0]
print(lr1)
lr3 = [m + n for m in 'ABC' for n in 'XYZ']
print(lr3)
#列出目录文件名
print('列出目录文件名')
import os # 导入os模块
lr4 = [x for x in os.listdir('.')] # os.listdir可以列出文件和目录
print(lr4)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
def f(x):
return x * x;
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 使用元类
class Hello(object):
def hello(self, name='world'):
print('Hello, %s.' % name)
h = Hello()
print(h.hello())
print(type(Hello))
print(type(h))
#type()函数可以查看一个类型或变量的类型,Hello是一个class,它的类型就是type,而h是一个实例,它的类型就是class Hello。
#我们说class的定义是运行时动态创建的,而创建class的方法就是使用type()函数。
#type()函数既可以返回一个对象的类型,又可以创建出新的类型,比如,我们可以通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义:
def fn(self,name='world'): #先定义函数
print('Hello,%s' % name)
Hello = type('Hello',(object,),dict(hello=fn)) #创建Hello类
h = Hello()
print(h.hello())
print(type(Hello))
print(type(h))
#要创建一个class对象,type()函数依次传入3个参数:
# class的名称;
# 继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
# class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。
#通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。
#正常情况下,我们都用class Xxx...来定义类,但是,type()函数也允许我们动态创建出类来,也就是说,动态语言本身支持运行期动态创建类,这和静态语言有非常大的不同
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 模块的文档注释,任何模块代码的第一个字符串都被视为模块的文档注释
' a test module '
__author__ = 'Michael' #使用__author__变量把作者写进去
import sys
def test():
args = sys.argv
if len(args) == 1:
print('Hello world!')
elif len(args) == 2:
print('Hello %s!' % args[1])
else:
print('Too many args !')
#当我们在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败,因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是运行测试。
if __name__ == '__main__':
test()
#作用域
#类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用
def _priviate_1(name):
print('Hello,%s' % name)
def _private_2(name):
return 'Hi,%s' % name
def greeting(name):
if len(name) > 3:
return _priviate_1(name)
else:
return _private_2(name)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
class Animal(object):
pass
# 大类:
class Mammal(Animal):
pass
class Bird(Animal):
pass
# 各种动物:
class Dog(Mammal):
pass
class Bat(Mammal):
pass
class Parrot(Bird):
pass
class Ostrich(Bird):
pass
class Runnable(object):
def run(self):
print('Running...')
class Flyable(object):
def fly(self):
print('Flying...')
class Dog(Mammal, Runnable):
pass
#MixIn的目的就是给一个类增加多个功能,这样,在设计类的时候,我们优先考虑通过多重继承来组合多个MixIn的功能,而不是设计多层次的复杂的继承关系。
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# mysql数据库操作
import mysql.connector
conn = mysql.connector.connect(host='192.168.2.182',port=33066,user='root', password='123456', database='test')
cursor = conn.cursor()
cursor.execute('select * from user where id = %s', ['1'])
values = cursor.fetchall()
print(values)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
#OOP面向对象编程
std1 = { 'name': 'Michael', 'score': 98 }
std2 = { 'name': 'Bob', 'score': 81 }
def print_score(std):
print('%s: %s' % (std['name'], std['score']))
print(print_score(std1))
print(print_score(std2))
class Student(object):
"""docstring for Student"""
def __init__(self, name,score):
self.name = name
self.score = score
def print_score(self):
print('%s:%s'% (self.name,self.score))
bart = Student('李唐',100)
lisa = Student('小明',87)
bart.print_score()
lisa.print_score()
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
# 面向对象(高级)
class Student(object):
pass
std = Student()
std.name="张三"
print(std.name)
#实例绑定一个方法
def set_age(self,age):
self.age = age
from types import MethodType
std.set_age = MethodType(set_age,std)
std.set_age(25)
print(std.age)
#给一个实例绑定的方法,对另一个实例是不起作用的
#为了给所有实例都绑定方法,可以给class绑定方法
def set_socre(self,score):
self.score = score
Student.set_socre = MethodType(set_socre,Student)
std.set_socre(99)
print(std.score)
std1 = Student()
std1.set_socre(88)
print(std1.score)
#Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性
class Student(object):
__slots__ = ('name','age')
s = Student()
s.name = '李理理'
print(s.name)
#使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
class GraduateStudent(Student):
pass
g = GraduateStudent();
g.score = 110
print(g.score)
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
#安装第三方模块,使用pip命令
#示例:图片裁剪 Pillow
#安装 pip install Pillow
#生成缩略图
from PIL import Image
im = Image.open('D:\\test.png')
print(im.format,im.size,im.mode)
im.thumbnail((200,100))
im.save('thumb.jpg','JPEG')
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
#Python内置的@property装饰器就是负责把一个方法变成属性调用的
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
#Python内置的@property装饰器就是负责把一个方法变成属性调用的
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self,value):
if not isinstance(value,int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 - 100!')
self._score = value
#@property的实现比较复杂,我们先考察如何使用。把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值
s = Student()
s.score = 60
print(s.score)
class Student(object):
@property
def birth(self):
return self._birth
@birth.setter
def birth(self, value):
self._birth = value
@property
def age(self):
return 2015 - self._birth
s = Student()
s.birth = 2000
#s.age = 20
print(s.age)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f = lazy_sum(1,3,5,7,9)
print(f)
print(f())
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# github:https://github.com/tangthis
sorder = sorted([20,1,9,-12,100,10])
print(sorder)
#key函数来实现自定义的排序
sorderByKey = sorted([20,1,9,2,-12,299],key=abs)
print(sorderByKey)
#字符串排序
sortStr = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
print(sortStr)
#逆向排序
sortStrReverse = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower,reverse=True)
print(sortStrReverse)
\ No newline at end of file
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
#第一行注释是为了告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释;
#第二行注释是为了告诉Python解释器,按照UTF-8编码读取源代码,否则,你在源代码中写的中文输出可能会有乱码。
print('包含中文字符str')
#获取字符整数表示
ord('A')
ord('中')
#chr()把编码转成对应字符
chr(66)
chr(25991)
#如果要在网络上传输,或者保存到磁盘上,就需要把str变为以字节为单位的bytes。
#bytes类型的数据用带b前缀的单引号或双引号表示
x = b'ABC'
#以Unicode表示的str通过encode()方法可以编码为指定的bytes
'ABC'.encode('ascii')
'中文'.encode('utf-8')
#要计算str包含多少个字符,可以用len()函数:
len('中文')
len('ABC')
#格式化输出
print('Hi,%s,you have $%d' % ('Michale',100000))
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册